[英]Python lxml xpath returns no output
我尝试在Python中使用lxml在网站上抓取特定元素。 您可以在下面找到我的代码,但是没有输出。
from lxml import html
webpage = 'http://www.funda.nl/koop/heel-nederland/'
page = requests.get(webpage)
tree = html.fromstring(page.content)
content = '//*[@id="content"]/form/div[2]/div[5]/div/a[8]/text()'
content = str(tree.xpath(content))
print content
您尝试剪贴的网站似乎不喜欢被剪贴。 他们利用各种技术来检测请求是来自合法用户还是来自机器人,并阻止访问(如果认为来自机器人)。 这就是为什么您的xpath找不到任何东西的原因,这就是为什么您应该重新考虑所做的事情的原因。
如果您决定继续,那么欺骗该特定网站的最简单方法似乎是向您的请求添加cookie。
首先,使用您的真实浏览器获取cookie字符串:
heel-nederland/
请求,然后单击 然后,修改程序以使用这些cookie:
import requests
from lxml import html
webpage = 'http://www.funda.nl/koop/heel-nederland/'
headers = {
'Cookie': '<string copied from browser>'
}
page = requests.get(webpage, headers=headers)
tree = html.fromstring(page.content)
selector = '//*[@id="content"]/form/div[2]/div[5]/div/a[8]/text()'
content = str(tree.xpath(selector))
print content
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.