【问题标题】:How to extract text with lxml in this scraper program?如何在这个爬虫程序中使用 lxml 提取文本?
【发布时间】:2013-07-24 17:56:51
【问题描述】:

我正在尝试从该页面上的特定元素中抓取文本数据(使用 scraperwiki)

import requests
from lxml import html

response = requests.get(http://portlandmaps.com/detail.cfm?action=Assessor&propertyid=R246274)

tree = html.fromstring(response.content)
owner = tree.xpath('/html/body/div[2]/table[1]/tbody/tr[11]/td[2]')

print owner.text

scraperwiki 控制台返回:

AttributeError: 'list' object has no attribute 'text'

我使用 Google Chrome 查找 XPath,但我认为 requests 使用与 chrome 相同的标准

【问题讨论】:

  • 问题本身就是为什么 owner 是一个列表。尝试打印出所有者而不是 owner.text 并在此处报告
  • 另外,您可能需要检查响应内容是什么。
  • response 给了我一个普通的 HTML 文档,XPath 把 owner 变成一个列表,这样正常吗? 'print len(owner)' 返回 0

标签: python lxml scraper scraperwiki


【解决方案1】:

那是因为你要找的东西都不存在。先试试父母。

然后,一旦可行,试试这个:

owner[0].text

如果您找不到/记住您想要的 tr,只需获取第 3 个索引的所有 td:

tree = html.fromstring(response.content)
owner = tree.xpath('/html/body/div[2]/table[1]/tbody/tr/td[2]')

texts = [o.text for o in owner]
print texts

然后,选择并相应地修改代码。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多