首页 > 解决方案 > 如何抓取网页中的所有链接?我的代码只抓取了一些链接

问题描述

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

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

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

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


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

试试这个,希望它有效。

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

推荐阅读