python - tree.xpath() 使用 lxml 库在 Webscraping 中返回空列表

标签 python web-scraping beautifulsoup youtube lxml

当你去:
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'))

最佳答案

如果请求不起作用,您可以使用 selenium。我最终使用 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)
URL fetched from anchor tag

关于python - tree.xpath() 使用 lxml 库在 Webscraping 中返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693980/

相关文章:

python - 我的查询不起作用 Postgresql-Python

Python - 从 ReactJS div 中抓取列表内容

python - bs4 是否检索整个网页,即使它需要物理滚动才能获取所有元素?

python - Scrapy 使用错误的编码,从网页向 JSON 添加额外的 html 标签

python - 如何从简单的html表格中提取行?

python - 如何将命令行输入写入 fabfile?

python - 获取 Tkinter 窗口大小

python - 我可以将我的文件命名为 logging.py

python - pickle 没有以正确的方式工作

Python3 : BeautifulSoup4 not returning expected value