前言今天给大家带来使用Python模拟登录京东图书商品数据抓取,废话不多说。开开心心开发工具Python版本:3.6.4相关模块:selenium模块time模块requests模块lxml模块csv模块环境搭建安装Python并添加到环境变量中,pip安装需要的相关模块。思路解析本文使用爬虫爬取京东图书和商品,并讲解如何爬取模拟登陆京东抓取数据1.获取页面信息类JdSpider(object):def__init__(self):self.i=0self.url="https://www.jd.com"self.browser=webdriver.Chrome(r"C:/python-3.9.6-embed-amd64/Application/chromedriver.exe")2.获取页面信息--转到具体产品页面defget_html(self):#self.browser.set_window_size(1200,800)#控制浏览器大小#self.browser.back()#浏览器后退#self.browser.forward()#浏览器前进self.browser.get(self.url)self.browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument",{"source":"""Object.defineProperty(navigator,'webdriver',{get:()=>undefined})"""})a=input('请输入您要的产品:')self.browser.find_element_by_xpath('//*[@id="key"]').send_keys(a)3.分析页面#分析页面定义parse_html(self):#将下拉菜单拉到底部,执行JS脚本self.browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')time.sleep(2)#提取一个listofallproductnodeobjectslilistli_list=self.browser.find_elements_by_xpath('//*[@id="J_goodsList"]/ul/li')结果展示4.创建csv,写header#createcsvfp=open('京东商品信息爬取.csv','wt',newline='',encoding='utf-8')#写头writer=csv.writer(fp)writer.writerow(('price','evaluation','publisher','商品信息',))forliinli_list:info_list=li.text.split('\n')ifinfo_list[0].startswith('Everyfull')orinfo_list[1].startswith('¥'):price=info_list[1]name=info_list[2]comment=info_list[3]shop=info_list[4]elifinfo_list[0].startswith('单品'):price=info_list[3]name=info_list[4]comment=info_list[5]shop=info_list[6]else:price=info_list[0]name=info_list[1]comment=info_list[2]shop=info_list[3]writer.writerow((price,comment,shop,name))print(price,comment,shop,name)结果展示