【问题标题】:Can I search multiple HTML elements within the soup.find_all() function?我可以在 soup.find_all() 函数中搜索多个 HTML 元素吗?
【发布时间】:2020-09-12 10:53:46
【问题描述】:

我正在尝试从网站上抓取浏览次数最多的头条新闻。我想要的文本的类选择器与页面上的其他项目共享常用词。例如,我想要标签和类“black_color”之间的文本。其他项目使用该标签并具有“color_black hover_color_gray_90”类,我不希望包括这些。我在想我可以使用更多的 HTML 元素来更具体,但我不确定如何合并它们。

from bs4 import BeautifulSoup

def getHeadlines():
    url = "https://www.bostonglobe.com/"

    source_code = requests.get(url)

    plainText = source_code.text

    soup = BeautifulSoup(plainText, "html.parser")

    #results = soup.find_all("h2",{"class":"headline"})
    results = soup.find_all("a",{"class":"black_color"})
    

    with open("headlines.txt", "w", encoding="utf-8") as f:
        for i in results:
            f.write(str(i.text + ' \n' + '\n'))
        

getHeadlines()

【问题讨论】:

  • 您能否提供一些示例数据和所需的提取输出?很难知道您的意思是“我想要标签和类之间的文本” - 类是标签的属性。例如,在您的代码中,您搜索类为'black_color'<a> 标记。获取它们之间的文本是什么意思?还有其他“使用标签并拥有类”的示例是什么?
  • 我想在此处嵌入文本:40 磅重的异国宠物猫在新罕布什尔州逍遥法外。此代码也存在于页面上,我不希望这些结果包含在我的输出中:Sports

标签: python web-scraping beautifulsoup


【解决方案1】:

我认为查看<a> 标签实际上可能比使用匹配的<h2> 更难,它有一个'headline' 类。

试试这个:

soup = BeautifulSoup(source_code.text, "html.parser")

for headline in soup.find_all("h2", class_="headline"):
    print(headline.text)

输出:

Boston College outbreak worries epidemiologists, students, community
Nantucket finds ‘community spread’ of COVID-19 among tradespeople The town’s Select Board and Board of Health will hold an emergency meeting at 10 a.m. Monday to consider placing restrictions on some of those trades, officials said Friday. 
Weddings in a pandemic: Welcome to the anxiety vortexNewlyweds are spending their honeymoons praying they don’t hear from COVID‐19 contact tracers. Relatives are agonizing over “damned if we RSVP yes, damned if we RSVP no” decisions. Wedding planners are adding contract clauses specifying they’ll walk off the job if social distancing rules are violated. 
Fauci says US should plan to ‘hunker down’ for fall and winter
Of struggling area, Walsh says, ‘We have to get it better under control’ 
...

看了一会,我觉得<a>这个标签实际上可能有一些类是动态添加的,BS不会接。仅搜索 color_black 类并排除 color_black hover_color_gray_90 类会产生您不想要的标题类(例如“体育”),即使当我查看实际网页源代码时,我发现它在你所指示的方式。

这通常是对页面进行加载后 CSS 更改的好兆头。 (我可能错了,但无论哪种情况,我都希望<h2> 方法能满足您的需求。)

【讨论】:

  • 感谢您的回复。如果您查看我的代码,我将 h2, class= 标题部分注释掉以尝试另一种方式。搜索该元素和类工作正常,它只会返回很多结果并包括我不想要的其他内容。我希望只是抓取“观看次数最多”列表,所以我只能得到大约 10 个结果而不是 50+。
  • 观看次数最多的列表是从一些数据库拉取、页面加载后动态呈现的。这意味着 BeautifulSoup 看不到它。您可以对此进行测试 - 包含 Most Viewed 的 <div> 具有特定的 id 值,在我的负载下,该值是 c0fhKlnQperj1CT。所以一旦你有了soup 对象,运行:soup.find(id="c0fhKlnQperj1CT").contents。您会看到只有一个 <span> 标记并分配了一个 'spacer' 类。但是,如果您在浏览器中查看实际网页中的 HTML,您会看到分隔符 <span> 以及一大堆额外的代码,用于加载 Most Viewed 表。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2016-08-06
相关资源
最近更新 更多