【问题标题】:Python lxml xpath no outputPython lxml xpath没有输出
【发布时间】:2016-03-25 20:56:07
【问题描述】:

出于教育目的,我正在尝试使用 lxml 和 Python 中的请求来抓取 this page

具体来说,我只想在页面上打印所有教授的研究领域。 这是我到目前为止所做的事情

import requests
from lxml import html

response=requests.get('http://cse.iitkgp.ac.in/index.php?secret=d2RkOUgybWlNZzJwQXdLc28wNzh6UT09')
parsed_body=html.fromstring(response.content)

for row in parsed_body.xpath('//div[@id="maincontent"]//tr[position() mod 2 = 1]'):
    for column in row.xpath('//td[@class="fcardcls"]/tr[2]/td/font/text()'):        
        print column.strip()    

但它没有打印任何东西。我在使用 xpaths 时遇到了很多困难,最初是在 chrome 中使用复制 xpath 功能。我按照以下 SO 问题/答案中所做的操作,对我的代码进行了相当多的清理,并在 xpaths 中删除了“tbody”。代码仍然返回一个空白。

1. Empty List Returned

2. Python-lxml-xpath problem

【问题讨论】:

    标签: python-2.7 xpath web-scraping python-requests lxml


    【解决方案1】:

    首先,内部包含所需数据的主要内容是通过 XHR 请求从不同的端点加载的 - 在您的代码中进行模拟。

    这是完整的工作代码打印名称和每个名称的研究领域列表

    import requests
    from lxml import html
    
    response = requests.get('http://cse.iitkgp.ac.in/faculty4.php?_=1450503917634')
    parsed_body = html.fromstring(response.content)
    
    for row in parsed_body.xpath('.//td[@class="fcardcls"]'):
        name = row.findtext(".//a[@href]/b")
        name = ' '.join(name.split())  # getting rid of multiple spaces
    
        research_areas = row.xpath('.//*[. = "Research Areas: "]/following-sibling::text()')[0].split(", ")
    
        print(name, research_areas)
    

    这里的想法是利用所有“教授块”都位于td元素和class="fcardcls"的事实。对于每个区块,从粗体链接文本中获取名称,从Research Areas: 粗体文本之后的以下字符串中获取研究区域。

    【讨论】:

    • 您的代码运行良好,我理解您所写的内容,谢谢。现在,我有几个问题: 1. 你是如何找到主要内容页面的,即this one 2. 在我的代码中,我写的 xpath 中的错误是什么?当我检查 chrome 的“检查”时,他们指向了正确的元素(研究领域)。
    • @humblenoob 好的,当然 - 1. 我刚刚使用了浏览器开发工具并检查了在页面加载期间发送了哪些请求; 2. 您的代码总体上在正确的轨道上——好吧,至少有一件事是内部 xpath 表达式必须以点开头才能特定于上下文。希望答案有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2016-03-07
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多