【问题标题】:How do I scrape all links in a webpage? My code only scrapes some of the links如何抓取网页中的所有链接?我的代码只抓取了一些链接
【发布时间】:2018-05-23 14:26:40
【问题描述】:

这是我抓取网页中所有链接的代码:

from bs4 import BeautifulSoup
import requests
import re

page = requests.get("http://www3.asiainsurancereview.com/News")
soup = BeautifulSoup(page.text, "html.parser")
for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
    print(link.get('href'))

links.close()

但它仅列出下拉菜单中存在的链接。这是为什么?为什么它没有“看到”页面中出现的新闻文章的链接?我实际上想刮掉所有的新闻文章。我尝试了以下方法来识别标签并抓取该标签中的新闻文章链接:

import requests
import re

links=open("Life_and_health_links.txt", "a")
page = requests.get("http://www3.asiainsurancereview.com/News")
soup = BeautifulSoup(page.text, "html.parser")

li_box = soup.select('div.col-sm-5 > ul > li > h5 > a')
for link in li_box:
    print(link['href'])

但是,这当然只显示该特定标签中的链接。为了列出其他标签中的链接,我必须多次运行此代码,指定我想要列出其链接的特定标签。但是,如何在所有标签中列出所有新闻文章的链接,并跳过不是新闻文章的链接?

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    你需要做一些研究来找到新闻链接的共同模式。

    试试这个,希望它有效。

    li_box = soup.select("div ul li h5 a")
    for a in li_box:
        print(a['href'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 2014-01-10
      • 2023-01-04
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多