使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件
需要使用Selenium库,如无这个库的话请使用pip命令自行安装
pip install selenium
还需要用到谷歌浏览器驱动,请自行下载对应版本驱动后填入下方代码需要处
/
from selenium import webdriver
import time
import csv
import re
from selenium.webdriver.support.wait import WebDriverWait
goodslinks=[]
def get_goodslink():#填入自己的浏览器驱动位置wd=webdriver.Chrome("")#打开京东口罩搜索页面wd.get("=口罩") time.sleep(4)#商品链接获取links=wd.find_elements_by_css_selector(".gl-item .gl-i-wrap .p-img a")for link in links:href_attribute('href')goodslinks.append(href)wd.close()def get_goodscomments(urls):#填入你的浏览器驱动位置wd=webdriver.Chrome("")for url in (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);") time.sleep(3)#设置显式等待,点击差评按钮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. +'n')wd.close()if __name__=="__main__":get_goodslink()get_goodscomments(goodslinks)
最开始让程序自行爬取商品名称创建txt文件时报错,搜索之后发现创建文件不能有非法字符,此时需要用re.sub()处理非法字符
rightName=re.sub(r"[/\:*?"<>|]", "_", goodsName)
博主仅为python新手,本篇博文仅供交流分享,如有不足之处欢迎各位大佬指点!
本文发布于:2024-02-05 06:17:28,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170726062063764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |