尝试使用 lxml.html 从网站的特定部分获取文本

Attempting to get the text from a certain part of a website using lxml.html

我有一些当前的 Python 代码应该使用 HTML 标签所在的 xpath 从网站的某个部分获取 HTML。

def wordorigins(word):
    pageopen = lxml.html.fromstring("http://www.merriam-webster.com/dictionary/" + str(word))
    pbody = pageopen.xpath("/html/body/div[1]/div/div[4]/div/div[1]/main/article/div[5]/div[3]/div[1]/div/p[1]")
    etybody = lxml.html.fromstring(pbody)
    etytxt = etybody.xpath('text()')
    etytxt = etytxt.replace("<em>", "")
    etytxt = etytxt.replace("</em>", "")
    return etytxt

此代码 returns 关于期望字符串或缓冲区的错误:

Traceback (most recent call last):
  File "mott.py", line 47, in <module>
    print wordorigins(x)
  File "mott.py", line 30, in wordorigins
    etybody = lxml.html.fromstring(pbody)
  File "/usr/lib/python2.7/site-packages/lxml/html/__init__.py", line 866, in fromstring
    is_full_html = _looks_like_full_html_unicode(html)
TypeError: expected string or buffer

想法?

xpath() 方法 returns 结果列表 fromstring() 需要一个字符串。

但是,您不需要重新解析文档的这一部分。只需使用您已经找到的内容:

def wordorigins(word):
    pageopen = lxml.html.fromstring("http://www.merriam-webster.com/dictionary/" + str(word))
    pbody = pageopen.xpath("/html/body/div[1]/div/div[4]/div/div[1]/main/article/div[5]/div[3]/div[1]/div/p[1]")[0]
    etytxt = pbody.text_content()
    etytxt = etytxt.replace("<em>", "")
    etytxt = etytxt.replace("</em>", "")
    return etytxt

请注意,我使用的是 text_content() 方法而不是 xpath("text()")

@alecxe 的回答中所述,xpath() 方法 return 在这种情况下匹配元素的列表,因此当您尝试将列表传递给 lxml.html.fromstring()。另一件需要注意的事情是,XPath 的 text() 函数和 lxmltext_content() 方法都不会 return 包含诸如 <em></em> 之类的标记的字符串。如果有的话,它们会自动去除标签,所以不需要这两行 replace() 。您可以简单地使用 text_content() 或 XPath 的 string() 函数(而不是 text()):

......
# either of the following lines should be enough
etytxt = pbody[0].xpath('string()')
etytxt = pbody[0].text_content()