[英]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
此代碼返回有關期望字符串或緩沖區的錯誤:
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()
方法返回一個結果列表, 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()
方法返回匹配元素的列表,因此當您嘗試將列表傳遞給lxml.html.fromstring()
時會出現錯誤。 另一件要注意的事情是,XPath 的text()
函數和lxml
的text_content()
方法都不會返回包含諸如<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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.