python之爬虫爬取VIP蔬菜网农产品价格行情(使用requests库 + HTML)
被爬取网站:http://www.vipveg.com/price/2017/baicai/m10d-1cta926by-1.html
爬取的时候只需要换链接即可,一个网站内通用
您目前所在位置:VIP蔬菜网首页 > 2017年蔬菜批发市场价格行情 > 2017年白菜价格行情
爬取代码:
import requests #导入请求库
import datetime
from lxml import etree
#要请求的url
url = "http://www.vipveg.com/price/2018/fanqie/"
#请求时,提交给服务器的客户端信息user-agent
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36','Cookie': 'ASP.NET_SessionId=yolmu555asckw145cetno0um'
}
response = requests.get(url, headers=headers)
html = etree.HTML(response.content.decode('utf-8'))
table = html.xpath("//table[2]//tr[position()>2]")
for i in table: # 遍历tr列表p = ''.join(i.xpath(".//td[1]//text()")) # 获取当前tr标签下的第一个td标签,并用text()方法获取文本内容,赋值给psl = ''.join(i.xpath(".//td[2]//text()"))sc = ''.join(i.xpath(".//td[3]//text()"))ll = ''.join(i.xpath(".//td[4]//text()"))lc = ''.join(i.xpath(".//td[5]//text()"))year = ''.join(i.xpath(".//td[6]//text()"))# print(p, sl, sc, ll, lc, year)data = { # 用数据字典,存储需要的信息'品种': ''.join(p.split()), # .split()方法在此处作用是除去p中多余的空格 '\xa0''批发市场': ''.join(sl.split()),'最低价格': ''.join(sc.split()),'最高价格': ''.join(ll.split()),'平均价格': ''.join(lc.split()),'发布时间': ''.join(year[0:4]+"年"+ year[5:7]+"月"+year[8:10]+"日") }print(data)