【问题标题】:How to find links within a specified class with Beautiful Soup如何使用 Beautiful Soup 在指定类中查找链接
【发布时间】:2016-11-20 05:59:50
【问题描述】:

我正在使用 Beautiful Soup 4 来解析新闻站点以获取正文中包含的链接。我能够找到包含链接的所有段落,但 paragraph.get('href') 为每个链接返回类型 none。我正在使用 Python 3.5.1。非常感谢任何帮助。

from bs4 import BeautifulSoup
import urllib.request
import re

soup = BeautifulSoup("http://www.cnn.com/2016/11/18/opinions/how-do-you-deal-with-donald-trump-dantonio/index.html", "html.parser")

for paragraph in soup.find_all("div", class_="zn-body__paragraph"):
    print(paragraph.get('href'))

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你真的想要这个吗?

    for paragraph in soup.find_all("div", class_="zn-body__paragraph"):
        for a in paragraph("a"):
           print(a.get('href'))
    

    请注意,paragraph.get('href') 会尝试在您找到的 <div> 标记中查找 属性 href。由于没有这样的属性,它返回None。很可能您实际上必须找到所有标签<a>,它是您的<div> 的后代(这可以使用paragraph("a") 完成,它是paragraph.find_all("a") 的快捷方式,然后对于每个元素<a> 看看他们的@987654331 @ 属性。

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 2017-05-31
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多