仅将 Twitter 用作示例并忽略它们具有完美可用的 API 的事实,以下脚本从用户页面获取当前的第 5 条推文。
import urllib2
from lxml import etree
xpathselector = "/html/body/div/div[2]/div/div[5]/div[2]/div/ol/li[5]/div/div/p"
url = "https://twitter.com/bmthofficial"
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
result = tree.xpath(xpathselector)
print result[0].text
在写这篇文章时它打印:
From 2.30pm, win tickets to Reading Festival, and introduce
现在,它打印了
的内容,我将如何去获取 P 的类名?它的 HTML 看起来像这样。<p class="js-tweet-text tweet-text">From 2.30pm, win tickets to Reading Festival, and introduce <a dir="ltr" class="twitter-atreply pretty-link" href="/bmthofficial"><s>@</s><b>bmthofficial</b></a> onstage!</p>
感谢任何帮助!谢谢!
最佳答案
关于Python - 从 lxml xpath 获取类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18348777/