我正在尝试使用LXML和Python从页面中获取值。
我遵循了一些有效的基本例子。但是我很难从相当复杂的(至少对我来说)网页中获取文本。
我想从此页面中获取关注者数量: http://twitter.com/aberdeencc
我想要追随者的完全值(在撰写本文时为10,623 - 而不是显示的10.6K。确切的值只显示为工具提示式鼠标悬停。
查看本节中的页面代码:
<a class="ProfileNav-stat ProfileNav-stat--link u-borderUserColor u-textCenter js-tooltip js-openSignupDialog js-nonNavigable u-textUserColor" data-nav="followers"
href="/AberdeenCC/followers" data-original-title="10,623 Followers">
<span class="ProfileNav-label">Followers</span>
<span class="ProfileNav-value" data-is-compact="true">10.6K</span>
</a>
我的代码是
from lxml import html
import requests
page = requests.get('http://twitter.com/aberdeencc')
tree = html.fromstring(page.text)
followers = tree.xpath('//span[@class="ProfileNav-stat ProfileNav-stat--link
u-borderUserColor u-textCenter js-tooltip js-openSignupDialog js-nonNavigable
u-textUserColor"]/text()')
print 'Followers: ', followers
但是返回一个空列表。
(我知道不需要单个值的列表,但我现在使用的是现有代码)
感谢您提供的任何指示
Watty
答案 0 :(得分:0)
>>> from lxml import etree
>>> import requests
>>> page = requests.get("https://twitter.com/aberdeencc")
>>> doc = etree.HTML(page.text)
>>> doc.xpath('//a[@data-nav="followers"]/@title')
['10,623 Followers']
答案 1 :(得分:0)
我建议不要在特定情况下使用xpath
。我认为CSS selector API更适合这种情况。这应该有效:
followers = tree.cssselect("a.ProfileNav-stat")[0].attrib["data-original-title"]
# followers = '10,623 Followers'
此方法需要安装cssselect
。
答案 2 :(得分:0)
我会依赖data-nav
属性来获取title
属性的值:
from lxml import html
import requests
page = requests.get('http://twitter.com/aberdeencc')
tree = html.fromstring(page.text)
followers = tree.xpath('//a[@data-nav="followers"]/@title')
print 'Followers: ', followers
打印:
Followers: ['10,623 Followers']
为了从followers
中提取实际数字,您可以使用正则表达式,然后使用locale.atoi()
将字符串解析为int
:
import locale
import re
from lxml import html
import requests
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
page = requests.get('http://twitter.com/aberdeencc')
tree = html.fromstring(page.text)
followers = tree.xpath('//a[@data-nav="followers"]/@title')[0]
followers = re.match(r'^([0-9,]+)\sFollowers$', followers).group(1)
followers = locale.atoi(followers)
print 'Followers:', int(followers)
打印:
Followers: 10623
此外,twitter提供了API,你可以通过python界面使用它,有多种选择可供选择: