涉及带有属性的 HTML 标签的 Python 网络抓取

标签 python beautifulsoup lxml screen-scraping

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

<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>

到目前为止,我一直在尝试使用 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)

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

编辑:我想我没有说得很清楚,但是我想在页面中抓取多个标签。

最佳答案

从你的问题中我不清楚为什么你需要担心 div 标签——如何做:

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

在您提供的 HTML 上,运行它会准确地发出:

####I want whatever is located here ###

这似乎是你想要的。也许您可以更好地准确指定您需要什么,而这个 super 简单的代码段不会做 - 多个 td 标记所有类 author 您需要考虑的(全部?只是一些?哪些?),可能缺少任何此类标签(在这种情况下你想做什么),等等。仅从这个简单的示例和过多的代码,很难推断出您的规范到底是什么;-)。

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

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

...也就是说,一点也不难!-)

关于涉及带有属性的 HTML 标签的 Python 网络抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1391657/

相关文章:

python - 如何使用 beautifulsoup 获取所有页面?

python - 如何使用 BeautifulSoup (python) 跳过 <ul> 的第一个元素?

python - 从 XML 中删除 ns0、ns1、ns2 命名空间 - Python

python - 在将 pymoo 中的 NSGA 2 求解到数据帧中时,如何保存一组主导解决方案?

python - mysql 向表中插入重复值

python - 如何在Python中乘以数组中每个元素的每个值?

python - aws 客户端 cognito list_users() 函数的分页替代方案

python - 超过最大递归深度。多处理和 bs4

python - 如何从 lxml.html.html5paser 元素标记内部删除 namespace 值

python - lxml 中的 POST 方法表单使用 submit_form 引发 TypeError