首页 > 解决方案 > 无法使用 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 文档这一事实有关吗?

我已经刮了几个网站,直到现在还没有遇到过这样的问题。

标签: pythonhtmlxmlbeautifulsoup

解决方案


您想要的数据和标签不会出现在 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]

推荐阅读