本文结构:
一、引言
二、代码分享
三、问题总结
这里的,教,程大家一起学习!在我的Python学习 qun:【前面9 8 4 】【中间6 3 2 】【后面5 7 9 】动动你的小指头把数字连起来即可,欢迎加入到学习队伍里,有许多正在提升自己的小伙伴, 大家对学习 Python编程有问题,可以随时问,大家多交流!
引言
这两天因为一些需求,研究了一下如何爬取京东商品数据。最开始还是常规地使用selenium库进行商品页的商品抓取,后来因为想要获取优惠信息,只能进入到商品详情页进行抓取,想着用selenium库模拟浏览器行为进行页面抓取速度有点慢,就改用了requests库直接发送请求,然后问题就来了:明明在页面看到了优惠满减字段,抓取的结果却是空白的。
百度研究了一番,总算找到了原因。最后因为商品抓取量不大,所以还是乖乖的使用了selenium库进行爬虫。
代码分享
爬虫代码如下:
# -*- coding: utf-8 -*-
"""
爬取京东商品排行榜商品信息
"""
fromseleniumimportwebdriver
frombs4importBeautifulSoup
importpandasaspd
importre
importtime
##京东排行榜地址:https://top.jd.com/
writer=pd.ExcelWriter(r"D:\python学习\京东排行榜商品.xlsx")##数据写入的文件
##使用selenium模拟浏览器登陆
#需要下载安装chromedriver
driver = webdriver.Chrome(r"C:\chromedriver.exe")
driver.set_page_load_timeout(60)#设置页面最大加载等待时间
category = ["手机","平板电脑"]#需要爬取的品类
category_url = ["https://top.jd.com/sale?cateId=653","https://top.jd.com/sale?cateId=2694"]#爬取品类的网页
forci,cinenumerate(category_url,start=0):
driver.get(c)#发送请求
time.sleep(3)
#################################获取排行榜信息###############################333
info_name =[]#商品信息
tag1 = []#标签一:x天最低
tag2 = []#标签二:自营/包邮/促销/赠品
tag3 = []#标签三:好评率
price = []#商品价格
link = []#商品详情页
bs = BeautifulSoup(driver.page_source,"html.parser")
sale_list = bs.findAll("li",class_=re.compile('saleitem'))
forsinsale_list:
info_name.append(s.find("p",class_ ="saleitem_info_name").get_text())
t = s.find("li",class_ ="top_mod_tag_item top_mod_tag_dj")
iftisnotNone:
tag1.append(t.get_text())
else:
tag1.append("")
t = s.find("li",class_ = re.compile("top_mod_tag_item top_mod_tag_[^(dj)]"))
iftisnotNone:
tag2.append(t.get_text())
else:
tag2.append("")
t = s.find("li",class_ ="top_mod_tag_item",text=re.compile("好评率.*"))
iftisnotNone:
tag3.append(t.get_text())
else:
tag3.append("")
price.append(s.find('p',class_ ="saleitem_info_price").get_text())
link.append(s.find('a',class_ ="saleitem_link").get("href"))
#################进入商品详情页,获取商品的优惠券########################
coupon = []
fori,linenumerate(link, start=1):
driver.get(r"https:"+ l)
time.sleep(3)
bs = BeautifulSoup(driver.page_source,"html.parser")
try:
coupon.append(bs.find("div",class_="summary").find("div",id ="summary-quan").find("span",class_ ="text").get_text())
except:
coupon.append("")
print("抓取品类:%s,第%d个商品优惠券信息完成"%(category[ci],i))
time.sleep(3)
data = pd.DataFrame({"商品信息":info_name,"标签一(x天最低)":tag1,"标签二(自营/包邮/促销