使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件
Selenium库需要使用Selenium库,如无这个库的话请使用pip命令自行安装
谷歌浏览器驱动pip install selenium
还需要用到谷歌浏览器驱动,请自行下载对应版本驱动后填入下方代码需要处
参考代码http://npm.taobao.org/mirrors/Chromedriver/
from selenium import webdriverimport timeimport csvimport refrom selenium.webdriver.support.wait import webdriverwaitgoodslinks=[]def get_goodslink(): #填入自己的浏览器驱动位置 wd=webdriver.Chrome("") #打开京东口罩搜索页面 wd.get("https://search.jd.com/Search?keyword=口罩") time.sleep(4) #商品链接获取 links=wd.find_elements_by_CSS_selector(".gl-item .gl-i-wrap .p-img a") for link in links: href=link.get_attribute('href') goodslinks.append(href) wd.close() def get_goodscomments(urls): #填入你的浏览器驱动位置 wd=webdriver.Chrome("") for url in urls: wd.get(url) time.sleep(3) #获取商品名称 goodsname=wd.find_element_by_CSS_selector(".itemInfo-wrap .sku-name").text #去除商品名的非法字符 rightname=re.sub(r"[\/\\:\*\?\"\<\>\|]", "_", goodsname) # 控制鼠标从上往下滑动到底部 wd.execute_script("window.scrollTo(0,document.body.scrollHeight);") #设置显式等待,点击差评按钮 webdriverwait(wd,3,0.2).until(lambda x:x.find_element_by_CSS_selector("#comment ul li:nth-child(7) a")).click() time.sleep(3) #获取差评 goodsComment=wd.find_elements_by_xpath('//div[@class = "tab-con"]/div[@ID = "comment-6"]//p') #写入文件名 with open("E:\python文件\badcomments\"+ rightname +'.txt','a+', enCoding='utf-8-sig') as f: #badcomments为文件夹名字 for comment in goodsComment: f.writelines(comment.text +'\n') wd.close() if __name__=="__main__": get_goodslink() get_goodscomments(goodslinks)
最开始让程序自行爬取商品名称创建txt文件时报错,搜索之后发现创建文件不能有非法字符,此时需要用re.sub()处理非法字符
rightname=re.sub(r"[\/\\:\*\?\"\<\>\|]", "_", goodsname)
实验结果写在最后博主仅为python新手,本篇博文仅供交流分享,如有不足之处欢迎各位大佬指点!
总结以上是内存溢出为你收集整理的使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件全部内容,希望文章能够帮你解决使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)