使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件
2021/6/9 22:22:05
本文主要是介绍使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用Python中的Selenium库爬取京东口罩第一页的差评
- 实验目的
- Selenium库
- 谷歌浏览器驱动
- 参考代码
- 实验结果
- 写在最后
实验目的
使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件
Selenium库
需要使用Selenium库,如无这个库的话请使用pip命令自行安装
pip install selenium
谷歌浏览器驱动
还需要用到谷歌浏览器驱动,请自行下载对应版本驱动后填入下方代码需要处
http://npm.taobao.org/mirrors/chromedriver/
参考代码
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("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文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战