gpt4 book ai didi

html - 使用xpath(python3)的href属性为空

转载 作者:行者123 更新时间:2023-12-03 17:26:33 26 4
gpt4 key购买 nike

在 python3 中使用 chrome 和 xpath,我尝试提取“href”属性的值 on this web page . “href”属性包含我感兴趣的电影预告片(法语中的“bande-annonce”)的链接。

Here is the html of the page, with the href I want in the <a> tag (highlighted in blue)

首先,使用 xpath,“a”标签似乎是“span”标签。事实上,使用这段代码:

response_main=urllib.request.urlopen("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html")
htmlparser = etree.HTMLParser()
tree_main = etree.parse(response_main, htmlparser)
tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/*')

我得到这个结果:
[<Element span at 0x111f70c08>]

所以“div”标签不包含“a”标签,而只是一个“span”标签。我读过浏览器中的 html 可视化并不总是反射(reflect)服务器发送的“真实”html。因此,我尝试使用此命令来提取 href:
    response_main=urllib.request.urlopen("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html")
htmlparser = etree.HTMLParser()
tree_main = etree.parse(response_main, htmlparser)
tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/span/@href')

不幸的是,这没有返回任何内容......当我使用以下命令检查“span”标签中的属性时:
tree_main.xpath('//*[@id=\"content-start\"]/article/section[3]/div[2]/div/div/div/div[1]/span/@*')

我得到了“class”属性的值,但没有关于“href”...:
['ACrL3ZACrpZGVvL3BsYXllcl9nZW5fY21lZGlhPTE5NTYwMDcyJmNmaWxtPTIzMTg3NC5odG1s meta-title-link']

我需要一些帮助来了解这里发生了什么。为什么“a”标签是“span”标签?对我来说最重要的问题是,如何提取“href”属性的值?

非常感谢你的帮助!

最佳答案

使用 JavaScript 动态生成的必需链接.与 urllib.request你只能得到初始HTML您需要的页面源HTML毕竟JavaScript被执行。

您可以使用 selenium + chromedriver 获取动态生成的内容:

from selenium import webdriver as web
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

driver = web.Chrome("/path/to/chromedriver")
driver.get("http://www.allocine.fr/film/fichefilm_gen_cfilm=231874.html")
link = wait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@class='meta-title']/a[@class='xXx meta-title-link']")))
print(link.get_attribute('href'))

关于html - 使用xpath(python3)的href属性为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42902505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com