【问题标题】:How do I selectively scrape hrefs from div tags?如何选择性地从 div 标签中抓取 href?
【发布时间】:2020-03-21 15:26:10
【问题描述】:

我正在尝试从新闻网站上抓取 URL。具体来说,它们是特定搜索词的搜索结果中列出的新闻文章的 URL。

我是 BeautifulSoup 的新手,我不知道如何有选择地只抓取带我到一篇文章的 href(当我尝试抓取 div 标签中的儿童 href 时,我只得到一个空集,并且当我抓取标签时,我得到的 URL 比我想要的要多。

有什么想法吗?

这是网页的链接: https://www.thenational.ae/search?q=aramco

这是我正在使用的代码。

import requests, random, re
from bs4 import BeautifulSoup as bs

url = "https://www.thenational.ae/search?q=aramco"
webpage = requests.get(url)
soup = bs(webpage.text, "html.parser")
for link in soup.find_all('h1'):
    print(link.get('href'))

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您需要了解 HTML 的结构。从结构中,您可以看到您需要的hrefs 是与small-article-desc 类相同的div 的孩子。所以基本上你是这样做的:

    import requests, random, re
    from bs4 import BeautifulSoup as bs
    
    url = "https://www.thenational.ae/search?q=aramco"
    webpage = requests.get(url)
    soup = bs(webpage.text, "html.parser")
    for div in soup.find_all('div', {"class": "small-article-desc"}):
        a = div.find_all('a')
        print(a[0].get('href'))
    

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 2015-12-04
      • 2016-01-16
      • 2022-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多