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

我正在尝试制作一个网络刮板,它将解析出版物的网页并提取作者.网页的骨架结构如下:
<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语句可能是多余的,但我只是复制了我目前在更多源文件中所拥有的内容.

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

解决方法

从你的问题我不清楚为什么你需要担心div标签 – 如何做:
soup = BeautifulSoup(html)
thetd = soup.find('td',attrs={'class': 'author'})
print thetd.string

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

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

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

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

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

……也就是说,没有太大的难度! – )

相关文章

vue阻止冒泡事件 阻止点击事件的执行 &lt;div @click=&a...
尝试过使用网友说的API接口获取 找到的都是失效了 暂时就使用...
后台我拿的数据是这样的格式: [ {id:1 , parentId: 0, name:...
JAVA下载文件防重复点击,防止多次下载请求,Cookie方式快速简...
Mip是什么意思以及作用有哪些