
本文旨在解决使用beautifulsoup进行网页抓取时遇到的空列表问题。我们将深入分析导致空列表的常见原因,特别是选择器不准确和代码结构不合理。教程将演示如何通过采用更精确的css选择器和优化迭代逻辑来构建健壮的抓取脚本,确保数据能够被正确提取,避免常见的抓取失败。
在使用BeautifulSoup进行网页内容抓取时,开发者常常会遇到一个令人困惑的问题:尽管目标网页内容清晰可见,但抓取结果却是一个空列表。这通常意味着我们的抓取逻辑未能成功定位并提取到预期的HTML元素。空列表的出现,往往是由于选择器不准确、HTML结构理解有误或代码迭代方式存在缺陷所致。
以下是一个可能导致空列表的初始抓取尝试示例:
import requests
from bs4 import BeautifulSoup
url = 'https://inshorts.com/en/read/technology'
news_data = []
news_category = url.split('/')[-1]
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
data = requests.get(url, headers=headers)
if data.status_code == 200:
soup = BeautifulSoup(data.content, 'html.parser')
# 尝试查找标题和文章内容
headlines = soup.find('div', class_=['news-card-title', 'news-right-box'])
articles = soup.find('div', class_=['news-card-content', 'news-right-box'])
# 检查并尝试组合数据
if headlines and articles and len(headlines) == len(articles): # 此处会出错
news_articles = [
{
'news_headline': headline.find_all('span', attrs={'itemprop': 'headline'}).string,
'news_article': article.find_all('div', attrs={'itemprop': 'articleBody'}).string,
'news_category': news_category
}
for headline, article in zip(headlines, articles)
]
news_data.extend(news_articles)
print(news_data) # 输出结果为空列表上述代码之所以会输出空列表,主要原因在于对BeautifulSoup的find()方法及其返回值的理解和使用存在偏差,以及后续逻辑的结构性问题:
为了解决上述问题并实现可靠的网页抓取,我们可以采用以下优化策略:
下面是基于这些优化策略的改进代码示例:
import requests
from bs4 import BeautifulSoup
url = 'https://inshorts.com/en/read/technology'
news_data = []
news_category = url.split('/')[-1]
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
data = requests.get(url, headers=headers)
if data.status_code == 200:
soup = BeautifulSoup(data.content, 'html.parser')
# 使用CSS选择器定位所有新闻文章的父级容器
# 这里的'[itemtype="http://schema.org/NewsArticle"]'是一个非常精确的选择器
# 它匹配所有具有指定itemtype属性的元素,通常代表一个独立的内容块
for article_container in soup.select('[itemtype="http://schema.org/NewsArticle"]'):
# 在每个文章容器内部,使用select_one()定位标题和文章主体
headline_element = article_container.select_one('[itemprop="headline"]')
article_body_element = article_container.select_one('[itemprop="articleBody"]')
# 检查元素是否存在,并使用get_text()提取内容
news_headline = headline_element.get_text(strip=True) if headline_element else "N/A"
news_article = article_body_element.get_text(strip=True) if article_body_element else "N/A"
news_data.append(
{
'news_headline': news_headline,
'news_article': news_article,
'news_category': news_category
}
)
print(news_data) # 将输出包含数据的列表当使用BeautifulSoup进行网页抓取时遇到空列表,通常是由于HTML元素选择器不够精确或数据迭代逻辑存在缺陷。通过深入理解目标网页的HTML结构,并利用强大的CSS选择器(如属性选择器)来精准定位包含完整数据记录的父级容器,然后在其内部安全地提取子元素,可以构建出高效且健壮的网页抓取脚本。同时,采用 get_text() 进行文本提取和适当的空值处理,将进一步提升代码的可靠性,确保数据能够被成功抓取。
以上就是BeautifulSoup网页抓取指南:避免空列表的常见陷阱与最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号