在Python中使用BeautifulSoup解析数据

2024-04-20 01:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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或者我需要使用Regex?如何继续遍历其他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'

Tags: 标记divhtmlallfindastroauthorsph
2条回答

因为link已经从iterable中获取,所以不需要子索引link——您只需执行link.contents[0]

print link.contents[0]使用两个单独的例子<div class="list-authors">产生:

Dacheng Lin
Ronald A. Remillard
Jeroen Homan
A.G. Kosovichev

所以我不确定我是否理解关于搜索其他div的评论。如果它们是不同的类,则需要分别执行soup.findsoup.findAll,或者只修改第一个soup.find

只需使用findAll作为divs链接

对于soup.findAll('div',attrs={'class':'list authors'})中的authordiv:

相关问题 更多 >