Gob*_*ffi 10 html python parsing 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>
Run Code Online (Sandbox Code Playgroud)
我的困惑之处在于,当我做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'
Run Code Online (Sandbox Code Playgroud)
Joh*_*ooy 13
只需使用findAll作为链接的divs链接
对于在sec.findAll中的authordiv('div',attrs = {'class':'list-authors'}):