Selenium + Headless Chrome + 爬取动态网页(踩坑)

科研项目需要在云端做爬虫爬取YouTube的评论,我先在Google Colab试水,需要用加入Headless参数,并且设置窗口大小(很关键),查了很多资料才发现是没有设置窗口大小。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1920x1080")
options.add_argument("start-maximised")
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://www.youtube.com/watch?v=yIYKR4sgzI8')

driver.execute_script('window.scrollTo(1, 500);')
time.sleep(5)

views_div = driver.find_element_by_xpath('//*[@id="info-contents"]')
views = views_div.find_element_by_xpath('//*[@class="view-count style-scope yt-view-count-renderer"]')

comment_div=driver.find_element_by_xpath('//*[@id="contents"]')
comments=comment_div.find_elements_by_xpath('//*[@id="content-text"]')

print(views.text)
for comment in comments:
    print(comment.text)

driver.close()

https://stackoverflow.com/questions/48257870/headless-chrome-with-selenium-can-only-find-ways-to-scroll-non-headless
https://testerhome.com/topics/15065
https://liaobu.de/python-selenium-chrome-headless-implements-automatically-present-gift-in-huya/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值