Task4 爬取腾讯新闻

爬取腾讯新闻

关于 ‘chromedriver’ executable needs to be in PATH 的解决办法
用 chrome 浏览器跑 selenium,执行以下脚本:

from selenium import webdriver
dr=webdriver.Chrome()
dr.maximize_window()
dr.get(‘http://www.baidu.com/’)

报错信息:WebDriverException: Message: ‘chromedriver’ executable needs to be in PATH

发现是 chromedriver.exe 文件放置的位置不对,我按网上查到的普遍 chrome 安装路径 C:\Program Files (x86)\Google\Chrome\Application,并加入环境变量 PATH
将放入该路径下,并将该路径加入到环境变量 PATH 中,问题得以解决。
可通过右键点击chrome浏览器图标–>属性–>目标,获取chrome的安装目录。

代码实现

import time
import random
from selenium import webdriver
from lxml import etree
driver = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application')
driver.get('https://news.qq.com/')#载入网址
#利用random对单次滚动距离、滚动时间进行选取,模拟人工操作。
#页面默认加载10条,这里实现页面滚动,动态加载。
for i in range(20):
    pixel = random.randint(800,1000)
    driver.execute_script(f'window.scrollBy(0,{pixel})')
    time.sleep(random.random()+1)
html = driver.page_source
tree = etree.HTML(html)
infos = tree.xpath('//ul[@class="list"]/li/div[@class="detail"]/h3/a')

infolist = []
count = 0

for i,info in enumerate(infos):
    title = info.xpath('text()')[0]
    href = info.xpath('@href')[0]
    # print(i+1,title,href)
    infolist.append([i+1,title,href])
    
html = driver.page_source
tree = etree.HTML(html)
infos = tree.xpath('//ul[@class="list"]/li/div[@class="detail"]/h3/a')

infolist = []
count = 0

for i,info in enumerate(infos):
    title = info.xpath('text()')[0]
    href = info.xpath('@href')[0]
    # print(i+1,title,href)
    infolist.append([i+1,title,href])
    

结果,由于配置原因,还在尝试,先打卡,后期补上

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值