1.安装类库
pip install -i 源 requests
pip install -i 源 lxml
2.步骤
1.获取页面信息
- 通过csv文件读取参数变量
2.提取页面元素
3.保存抓取内容
3.脚本
import requests
from lxml import etree
import csv
def get_page(url):
res = requests.get(url)
code = res.apparent_encoding
res.encoding = "gbk"
return res.text
def get_element(content, path_str):
listcont = []
doc = etree.HTML(content)
for i in range(1, 11):
ele = doc.xpath(path_str + str(i) + ']/p/text()')[0]
listcont.append(str(i)+ele+'\n')
return listcont
def save_element(listcont):
file = open("spider.txt", "a", encoding='utf-8')
file.write('\n'.join(listcont) + "\n")
file.close()
if __name__ == '__main__':
file_csv = open('test1.csv', 'r')
rows = csv.reader(file_csv)
i = 0
for row in rows:
i = i + 1
path_str = row[1]
if i == 1 or i == 2:
url = row[0]
print(url)
print(path_str)
content = get_page(url)
listcont = get_element(content, path_str)
print(listcont)
save_element(listcont)
else:
for i in range(3, 10):
url = row[0] + str(i-1) + '.html'
print(url)
print(path_str)
content = get_page(url)
listcont = get_element(content, path_str)
print(listcont)
save_element(listcont)
附件:test1.csv http://www.testing.com/html/04/category-catid-104.html,/html/body/div[6]/div[1]/div[ http://www.testing.com/html/16/category-catid-116.html,/html/body/div[4]/div/div[ http://www.testing.com/html/04/category-catid-104-page-,/html/body/div[6]/div[1]/div[ http://www.testing.com/html/16/category-catid-116-page-,/html/body/div[4]/div/div[
|