在Python中使用BeautifulSoup解析数据
我正在尝试使用BeautifulSoup来解析一个DOM树,并提取作者的名字。下面是一些HTML代码片段,展示了我想要抓取的代码结构。
<html>
<body>
<div class="list-authors">
<span class="descriptor">Authors:</span>
<a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1">Dacheng Lin</a>,
<a href="/find/astro-ph/1/au:+Remillard_R/0/1/0/all/0/1">Ronald A. Remillard</a>,
<a href="/find/astro-ph/1/au:+Homan_J/0/1/0/all/0/1">Jeroen Homan</a>
</div>
<div class="list-authors">
<span class="descriptor">Authors:</span>
<a href="/find/astro-ph/1/au:+Kosovichev_A/0/1/0/all/0/1">A.G. Kosovichev</a>
</div>
<!--There are many other div tags with this structure-->
</body>
</html>
我有点困惑的是,当我使用soup.find时,它只找到我搜索的div标签的第一个出现位置。之后,我又搜索了所有的'a'链接标签。在这个阶段,我该如何从每个链接标签中提取作者的名字并打印出来呢?有没有办法用BeautifulSoup做到这一点,还是说我需要使用正则表达式?我该如何继续遍历其他的div标签并提取作者的名字呢?
import re
import urllib2,sys
from BeautifulSoup import BeautifulSoup, NavigableString
html = urllib2.urlopen(address).read()
soup = BeautifulSoup(html)
try:
authordiv = soup.find('div', attrs={'class': 'list-authors'})
links=tds.findAll('a')
for link in links:
print ''.join(link[0].contents)
#Iterate through entire page and print authors
except IOError:
print 'IO error'
2 个回答
1
因为link
已经从一个可迭代的对象中取出来了,所以你不需要再用下标去取link
的内容——你可以直接用link.contents[0]
。
用你新的例子,里面有两个不同的<div class="list-authors">
,执行print link.contents[0]
会得到:
Dacheng Lin Ronald A. Remillard Jeroen Homan A.G. Kosovichev
所以我不太明白关于搜索其他div的评论。如果它们是不同的类,你要么需要单独使用soup.find
和soup.findAll
,要么就修改你最开始的soup.find
。
13
只需要对这个 div 使用 findAll,就像你对链接使用的一样。
比如,你可以这样写:对于每一个叫 'list-authors' 的 div,使用 soup.findAll('div', attrs={'class': 'list-authors'})。