问题描述
我尝试使用此代码获得兄弟姐妹,知道为什么不打印它吗?
url = 'http://www.journaldunet.com/management/ville/lille/ville-59350/immobilier'
res = session.get(url)
price = lxml.html.fromstring(res.text).xpath("//text/tspan[text()='Prix médian']/following-sibling::tspan[3]/text()")
print(res.status_code,price)
在这个位于 http://www.journaldunet.com/management/ville/lille/ville-59350/immobilier 中的 html
<text x="8" style="font-size:14px;color:#333333;fill:#333333;" y="22">
<tspan style="font-weight:bold">Prix médian</tspan>
<tspan style="fill:#3f85f2" x="8" dy="17">●</tspan>
<tspan dx="0"> Lille: </tspan>
<tspan style="font-weight:bold" dx="0">2 968 euros</tspan>
</text>
它返回的不是价格,而是...
200 []
解决方法
因为,该 html 片段不在 res.text
输出字符串中。 (你可以自己检查)。它是由 javascript 在浏览器上动态创建的。
为了能够捕获动态页面内容(例如这个),您应该使用 Selenium。它基本上将网页加载到真正的浏览器(如 firefox、chrome 等)中,让浏览器完成其渲染工作,并让您从那里获取数据。
这是一个很好的教程,如何使用和抓取网页内容。
https://towardsdatascience.com/how-to-use-selenium-to-web-scrape-with-example-80f9b23a843a