【问题标题】:Parsing out data using BeautifulSoup in Python在 Python 中使用 BeautifulSoup 解析数据
【发布时间】:2023-03-09 15:37:01
【问题描述】:

我正在尝试使用 BeautifulSoup 解析 DOM 树并提取作者姓名。下面是 HTML 的 sn-p,用于显示我将要抓取的代码的结构。

<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'

【问题讨论】:

    标签: python html parsing beautifulsoup


    【解决方案1】:

    由于link 已经从可迭代对象中获取,因此您无需对link 进行子索引——您只需对link.contents[0] 进行子索引即可。

    print link.contents[0] 与您的新示例以及两个单独的 &lt;div class="list-authors"&gt; 产生:

    林大成
    罗纳德·A·雷米拉德
    杰伦·霍曼
    A.G.科索维切夫
    

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

    【讨论】:

    • 如果还有更多的 div 标签,我该如何遍历这些标签?
    • 如果你按 CSS 类搜索,你会得到一个元素列表,你可以使用 for 循环进行迭代(参见:crummy.com/software/BeautifulSoup/bs4/doc/…)。做类似的事情:authordiv = soup.find('div', class_ = 'list-authors').
    【解决方案2】:

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

    for authordiv in soup.findAll('div', attrs={'class': 'list-authors'}):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多