微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Python中的Selenium库爬取京东口罩第一页的差评,以商品名称保存为txt文件

使用Python中的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)

实验结果

在这里插入图片描述

ShiYu Liu

写在最后

博主仅为python新手,本篇博文仅供交流分享,如有不足之处欢迎各位大佬指点!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐