python - 无法使用 Python 的 Beautiful Soup 从特定的 span 标签中提取文本
问题描述
我目前正在抓取该网站以构建汽车数据集,并且我构建了一个方程式,用于在抓取时循环浏览网站的每个页面。但是,我无法提取完成这项工作所需的文本。
下面的代码片段是我要抓取的标签。我需要获取站点上的车辆数量。
<span class="d-none d-sm-inline">166 Vehicles</span>
下面是我用来抓取该元素的代码:
# Packages
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import requests
print("Started web scrape...")
limit = 10
start = 0 #increment by limit
website = requests.get(f'https://www.sosubaru.com/new-inventory/index.htm?start={start}')
soup = BeautifulSoup(website.text, 'html.parser')
inventory_count = soup.select("span.d-none.d-sm-inline")[0].string
print(inventory_count)
此代码返回以下内容:
Started OR_GP_Roe_Motors web scrape...
Traceback (most recent call last):
File "c:/mypath...", line 16, in <module>
inventory_count = soup.select("span.d-none.d-sm-inline")[0].string
IndexError: list index out of range
然后我通过返回soup.select给我的所有内容来检查为什么我得到了那个错误代码:
inventory_count = soup.select("span.d-none.d-sm-inline")
print(inventory_count)
返回:
Started web scrape...
[]
为什么它给我一个空列表?
然后我告诉它打印网站上的每个跨度标签,看看它是否存在。结果打印出许多跨度标签,但不包括我正在寻找的标签。为什么我不能用漂亮的汤发现它?是我正在使用的解析器吗?我尝试使用“lxml”作为解析器,但它没有改变任何东西。这与网站是 html xmls 文档这一事实有关吗?
我已经刮了几个网站,直到现在还没有遇到过这样的问题。
解决方案
您想要的数据和标签不会出现在 html 源代码中,这意味着它们是由 javascript 添加的。您可以使用 selenium 在呈现页面后获取页面源,也可以使用 requests_html,它具有类似于 BeautifulSoup 的 API,并且可以选择在抓取页面之前呈现页面的 javascript。
from requests_html import HTMLSession
s = HTMLSession()
r = s.get(url)
r.html.render()
r.find . . . [whatever you want to search for]
推荐阅读
- ionic-framework - 在 ionic 4 App 上显示从 firebase 检索的照片
- mysql - 使用 group by 对特定列进行 SUM 以及如何避免从中加入最少的表值?
- sapui5 - 什么是部件:和路径:在 sapui5 中,为什么要使用它们?
- c# - Nuget包安装报错:Install-Package Google.Apis.Drive.v3
- ruby-on-rails - 如何通过 ActiveMerhant StripeGateway 获取客户 ID -(Ruby on Rails)
- c# - 从数据库中获取下拉列表选择的值
- sql-server - 在 SQL Server 上报告以前的记录
- react-native - 如何在 ReactNative 中访问另一个控件中的一个控件属性
- node.js - 如何使用 npm run build 修复此错误?
- docker - 使用 docker 映像部署时,容器的 Web 应用程序仅显示默认页面