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

Posted

技术标签:

【中文标题】使用xpath(python3)的href属性为空【英文标题】:href attribute empty using xpath (python3) 【发布时间】:2017-08-11 15:59:43 【问题描述】:

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

首先,使用 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 可视化并不总是反映服务器发送的“真实”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”属性的值?

非常感谢您的帮助!

【问题讨论】:

【参考方案1】:

使用javascript 动态生成的必需链接。使用urllib.request,您只能获得初始的HTML 页面源,而在执行完所有JavaScript 之后,您需要HTML

您可以使用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'))

【讨论】:

感谢@Andersson 的提示,我正在使用 Anaconda 和 Spyder 在 python3 中进行编码。所以我在 Anaconda 中添加了 selenium 3.3.1 和 chromedriver 2.24.1。 最后一个问题!每次我使用此命令时: drive = web.chrome() ,都会打开一个 chrome 浏览器。你知道在打印href后关闭它的方法吗? (肯定有命令行)如果多次使用此命令,恐怕会出现问题:) 您可以使用driver.close()关闭当前打开的浏览器窗口或driver.quit()关闭浏览器并停止chromedriver

以上是关于使用xpath(python3)的href属性为空的主要内容,如果未能解决你的问题,请参考以下文章

Python3-Selenium自动化测试框架之xpath元素定位

Python3 爬虫XPath Helper的安装与使用

Python3编写网络爬虫05-基本解析库XPath的使用

Appium + Python3之安卓8.1,使用xpath定位不到元素

《python3网络爬虫开发实战》--解析库的使用

Selenium2+Python3.6实战:定位下拉菜单出错,如何解决?用select或xpath定位。