python - 在 Python 中使用 BeautifulSoup 解析数据

标签 python html 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>

我感到困惑的一点是,当我执行 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'

最佳答案

只需将 findAll 用于您为链接所做的 div 链接

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

关于python - 在 Python 中使用 BeautifulSoup 解析数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1501690/

相关文章:

java - 使用第一行文本值java获取第二行xml

python-docx - 如何重新启动列表刻字

html - 出现在 div 中的元素不应该是 : HTML

javascript - 无法使用 jquery-ui.js 通过鼠标调整分层 iframe 的大小

html - 如何解决这个重叠 div 问题并理解这个概念?

java - 解析命令行并将其更改为 Char 或 Boolean

javascript - DOMParser - 获取元素样式

python - PyEnchant:使用个人单词列表拼写检查文本 block

python - 如何输出仅包含特定颜色范围的图像?

python - 删除 <select> 元素的正则表达式