【问题标题】:tree.xpath() returns empty list in Webscraping using lxml librarytree.xpath() 使用 lxml 库在 Webscraping 中返回空列表
【发布时间】:2020-05-09 08:41:39
【问题描述】:

当你去: https://www.youtube.com/feed/trending

3个按钮:音乐游戏电影出现

我想选择音乐元素的<a> 标签。所以我可以从中提取href值。我使用了下面的代码,但它一直给我一个空列表。


from urllib.request import urlopen
from lxml import etree

url =  "https://www.youtube.com/feed/trending"

response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
print(tree.xpath('//*[@id="contents"]/ytd-channel-list-sub-menu-avatar-renderer[1]/a'))

【问题讨论】:

  • 我不希望这些按钮会出现在第一个 HTML 有效负载中。您还必须运行 javascript,以便加载按钮。使用开发人员控制台(网络选项卡)找出您从单个 url 获得的信息。根据我的快速检查,我的假设似乎是正确的。
  • @rene 所以伙计,你是说我要选择的这些元素是由 js 创建的,我得到了空列表,因为它还没有加载?有没有我可以研究的主题/功能来完全用它的 js 加载网站。我已经搜索了一段时间,但我得到的只是硒。
  • 好吧,伙计,我不知道,我不是 python 开发人员,也不熟悉 Beatifulsoup。 Selenium 使用了一个真正的浏览器,所以这就是你经常看到的原因。我不知道有任何开箱即用的选项不使用已安装的网络浏览器来完成加载资源、执行其 javascript 并为您提供 DOM 的繁重工作。

标签: python web-scraping beautifulsoup youtube lxml


【解决方案1】:

如果请求不起作用,您可以使用 selenium。我最终使用硒尝试过它,它工作得完美无缺。以下是您可以参考的代码。

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


URL = "https://www.youtube.com/feed/trending"

chrome_options = Options()
driver = webdriver.Chrome("./chromedriver/chromedriver.exe", options=chrome_options)#download chrome driver and add path here.
driver.maximize_window()

driver.get(URL)

wait1 = WebDriverWait(driver, 200)
wait1.until(EC.presence_of_element_located((By.XPATH, '//*[@id="img"]')))
print('-' * 100)
print(driver.find_element_by_xpath('//*[@id="contents"]/ytd-channel-list-sub-menu-avatar-renderer[1]/a').get_attribute('href'))
print('-' * 100)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2019-07-29
    相关资源
    最近更新 更多