涉及带有属性的HTML标记的Python Web抓取

Gob*_*ffi 7 python lxml screen-scraping beautifulsoup

我正在尝试制作一个网络刮板,它将解析出版物的网页并提取作者.网页的骨架结构如下:

<html>
<body>
<div id="container">
<div id="contents">
<table>
<tbody>
<tr>
<td class="author">####I want whatever is located here ###</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在尝试使用BeautifulSoup和lxml来完成这项任务,但我不知道如何处理这两个div标签和td标签,因为它们具有属性.除此之外,我不确定我是否应该更多地依赖于BeautifulSoup或lxml或两者的组合.我该怎么办?

目前,我的代码如下所示:

    import re
    import urllib2,sys
    import lxml
    from lxml import etree
    from lxml.html.soupparser import fromstring
    from lxml.etree import tostring
    from lxml.cssselect import CSSSelector
    from BeautifulSoup import BeautifulSoup, NavigableString

    address='http://www.example.com/'
    html = urllib2.urlopen(address).read()
    soup = BeautifulSoup(html)
    html=soup.prettify()
    html=html.replace('&nbsp', '&#160')
    html=html.replace('&iacute','&#237')
    root=fromstring(html)
Run Code Online (Sandbox Code Playgroud)

我意识到很多import语句可能是多余的,但我只是复制了我目前在更多源文件中所拥有的内容.

编辑:我想我没有说清楚,但我在页面中有多个标签,我想要刮.

Ale*_*lli 11

从你的问题我不清楚为什么你需要担心div标签 - 做什么只是:

soup = BeautifulSoup(html)
thetd = soup.find('td', attrs={'class': 'author'})
print thetd.string
Run Code Online (Sandbox Code Playgroud)

在您提供的HTML上,运行此命令完全发出:

####I want whatever is located here ###
Run Code Online (Sandbox Code Playgroud)

这似乎是你想要的.也许你可以更准确地指定你需要的东西,这个超级简单的代码片段没有 - 你需要考虑的所有tdauthor的多个标签(所有?只是一些?哪些?),可能缺少任何这样的标签(在这种情况下你想做什么),等等.很难从这个简单的例子和​​过多的代码中推断出你的规范到底是什么;-).

编辑:如果,根据OP的最新评论,有多个这样的td标签,每个作者一个:

thetds = soup.findAll('td', attrs={'class': 'author'})
for thetd in thetds:
    print thetd.string
Run Code Online (Sandbox Code Playgroud)

......也就是说,没那么难! - )


cap*_*ing 6

或者您可能正在使用pyquery,因为BeautifulSoup不再被主动维护,请参阅http://www.crummy.com/software/BeautifulSoup/3.1-problems.html

首先,安装pyquery

easy_install pyquery
Run Code Online (Sandbox Code Playgroud)

然后你的脚本就像这样简单

from pyquery import PyQuery
d = PyQuery('http://mywebpage/')
allauthors = [ td.text() for td in d('td.author') ]
Run Code Online (Sandbox Code Playgroud)

pyquery使用jQuery中熟悉的css选择器语法,我发现它比BeautifulSoup更直观.它使用下面的lxml,比BeautifulSoup快得多.但是BeautifulSoup是纯粹的python,因此也适用于谷歌的应用程序引擎


小智 5

lxml库现在是在python中解析html的标准.界面起初看起来很尴尬,但它对它的作用非常有用.

你应该让libary处理xml专业,比如那些转义和实体;

import lxml.html

html = """<html><body><div id="container"><div id="contents"><table><tbody><tr>
          <td class="author">####I want whatever is located here, eh? &iacute; ###</td>
          </tr></tbody></table></div></div></body></html>"""

root = lxml.html.fromstring(html)
tds = root.cssselect("div#contents td.author")

print tds           # gives [<Element td at 84ee2cc>]
print tds[0].text   # what you want, including the 'í'
Run Code Online (Sandbox Code Playgroud)