使用python extract-specific d在LXML中进行屏幕抓取

2024-06-26 10:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在过去的几个小时里,我一直在尝试编写一个程序,它可以完成我认为非常简单的任务:

  1. 程序要求用户输入(比如“幸福”类型)
  2. 程序使用此格式查询thinkexist网站(“http://thinkexist.com/search/searchquote.asp?搜索=用户输入
  3. 程序从网站返回第一个引用。在

我尝试过在lxml中使用Xpath,但是没有经验,而且每个构造都返回一个空数组。在

引用的实际内容似乎包含在类“sqq”中

如果我通过Firebug导航站点,单击DOM选项卡,就会发现引用是在textNode属性“wholeText”或“textContent”中——但我不知道如何在程序上使用这些知识。在

有什么想法吗?在


Tags: 用户程序comhttp类型search网站格式
3条回答

如果不需要通过XPath实现,可以使用这样的BeautifilSoup库(让myXml变量包含页面HTML源):

soup = BeautifulSoup(myXml)
for a in soup.findAll(a,{'class' : 'sqq'}):
  # this is your quote
  print a.contents

不管怎样,阅读BS文档,它对于一些不需要XPath功能的抓取需求可能非常有用。在

您可以打开html源代码来找到您要查找的确切类。例如,要获取页面上遇到的第一个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
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()

。。。如果你输入“莎士比亚”,它就会返回

^{pr2}$

相关问题 更多 >