繁体   English   中英

Python lxml xpath不返回任何输出

[英]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字符串:

  1. 开启新分页
  2. 开放开发人员工具
  3. 转到开发人员工具中的“网络”标签
  4. 如果网络标签为空,请刷新页面
  5. 查找对heel-nederland/请求,然后单击
  6. 在“请求标题”中,您将找到cookie字符串-它很长,并且包含许多看似随机的字符。 复制它

然后,修改程序以使用这些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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM