python - 如何抓取网页中的所有链接?我的代码只抓取了一些链接
问题描述
这是我抓取网页中所有链接的代码:
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'])
但是,这当然只显示该特定标签中的链接。为了列出其他标签中的链接,我必须多次运行此代码,指定我想要列出其链接的特定标签。但是,如何在所有标签中列出所有新闻文章的链接,并跳过不是新闻文章的链接?
解决方案
你需要做一些研究来找到新闻链接的共同模式。
试试这个,希望它有效。
li_box = soup.select("div ul li h5 a")
for a in li_box:
print(a['href'])
推荐阅读
- bdd - 没有强制参数的场景的API测试,响应将是错误代码和消息
- embedded - I2C:可以同时发生多个 I2C 错误吗?
- javascript - Pass JavaScript array to PHP
- python - 从电子邮件转换字符串
- javascript - How can you console.log tab?
- list - following the class correctly but the code is not accepted
- php - How to include workspcace project folder in run URLs in Ecplise for PHP?
- java - Is calling close() on object returned by MockitoAnnotations.openMocks(Object) is mandatory?
- typescript - 根据未定义检查参数,但编译器仍然警告 TS2532
- xcode - 从 Flutter 项目中删除蓝牙使用