使用Python和LXML进行屏幕抓取--提取特定数据
我这几小时一直在尝试写一个程序,做的事情我原以为会非常简单:
- 程序会询问用户输入(比如说输入“快乐”)
- 程序会用这个格式去查询网站 thinkexist(“http://thinkexist.com/search/searchQuotation.asp?search=用户输入”)
- 程序会返回网站上的第一条引用语。
我试着用 lxml 的 Xpath,但我没有经验,每次构造出来的结果都是空的。
实际上,引用语的内容似乎是在一个叫 "sqq" 的类里面。
如果我通过 Firebug 浏览这个网站,点击 DOM 标签,似乎引用语在一个叫 "wholeText" 或 "textContent" 的文本节点属性里——但我不知道怎么把这些知识用到程序里。
有没有什么想法?
3 个回答
1
你可以打开网页的源代码,找到你想要的具体类名。例如,如果你想获取页面上第一个出现的StackOverflow用户名,可以这样做:
#!/usr/bin/env python
from lxml import html
url = 'http://stackoverflow.com/questions/4710307'
tree = html.parse(url)
path = '//div[@class="user-details"]/a[@href]'
print tree.findtext(path)
# -> Parseltongue
# OR to print text including the text in children
a = tree.find(path)
print a.text_content()
# -> Parseltongue
6
import lxml.html
import urllib
site = 'http://thinkexist.com/search/searchquotation.asp'
userInput = raw_input('Search for: ').strip()
url = site + '?' + urllib.urlencode({'search':userInput})
root = lxml.html.parse(url).getroot()
quotes = root.xpath('//a[@class="sqq"]')
print quotes[0].text_content()
In real life, unlike in Shakespeare, the sweetness
of the rose depends upon the name it bears. Things
are not only what they are. They are, in very important
respects, what they seem to be.
... 如果你输入'莎士比亚',它会返回
1
如果你不一定要通过XPath来实现这个功能,你可以使用BeautifulSoup这个库,像这样使用(让myXml
变量包含页面的HTML源代码):
soup = BeautifulSoup(myXml)
for a in soup.findAll(a,{'class' : 'sqq'}):
# this is your quote
print a.contents
无论如何,建议你看看BeautifulSoup的文档,它对于一些不需要XPath强大功能的网页抓取需求可能非常有用。