python - 网页抓取新闻网站时出现索引错误
问题描述
我一直在尝试对新闻文章的标题进行网络抓取,但在以下代码中遇到“索引错误”。我只在最后一行代码中遇到问题。
import requests
from bs4 import BeautifulSoup
URL= 'https://www.ndtv.com/coronavirus?pfrom=home-mainnavgation'
r1 = requests.get(URL)
coverpage = r1.content
soup1 = BeautifulSoup(coverpage, 'html5lib')
coverpage_news = soup1.find_all('h3', class_='item-title')
coverpage_news[4].get_text()
这是错误:
IndexError Traceback (most recent call last)
<ipython-input-10-f7f1f6fab81c> in <module>
6 soup1 = BeautifulSoup(coverpage, 'html5lib')
7 coverpage_news = soup1.find_all('h3', class_='item-title')
----> 8 coverpage_news[4].get_text()
IndexError: list index out of range
解决方案
用于soup1.select()
搜索匹配 CSS 选择器的嵌套元素:
coverpage_news = soup1.select("h3 a.item-title")
这将找到一个a
元素class="item-title"
的后代h3
元素。
推荐阅读
- javascript - 尝试使用pouchDB,说我认为它没有定义
- java - 如何使用 Java GUI 在标签中打印 for 循环
- python - Django Postgre ProgrammingError Sum(text)
- javascript - 将 SVG D3 js 导出为 PNG 或 JPEG 并通过电子邮件发送
- tableau-api - 如何在 TABLEAU 中组合创建三个条形图和折线图
- react-native - 从 Web 视图打开带有 PHAsset URI 的文件
- performance - 每次运行代码都会变慢 (PowerPoint VSTO)
- javascript - 尝试在 Django 应用程序的 js 文件中导入 vue.js 时出现“未捕获的语法错误:无法在模块外使用 import 语句”
- sql - 加入两个表以获取匹配的记录和不匹配的记录
- html - 反应中文本输入的动态颜色