无法使用 Python 的 Beautiful Soup 从特定的 span 标签中提取文本

时间:2021-02-06 00:34:07

标签: python html xml beautifulsoup

我目前正在抓取 this website 以构建汽车数据集,并且我构建了一个方程式来在抓取时循环浏览网站的每个页面。但是,我无法提取完成这项工作所需的文本。

下面的代码片段是我试图抓取的标签。我需要获取网站上的车辆数量。

<span class="d-none d-sm-inline">166 Vehicles</span>

This image shows the site's element that I am trying to scrape

以下是我用来抓取该元素的代码:

# 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...
[]

为什么它给我一个空列表?

然后我告诉它打印出网站上的每个 span 标签,看看它是否在那里。结果打印出许多跨度标签,但不包括我正在寻找的标签。为什么我用美丽的汤检测不到它?它是我正在使用的解析器吗?我尝试使用 'lxml' 作为解析器,但它没有改变任何东西。和网站是html xmls doc有关系吗?

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

1 个答案:

答案 0 :(得分:1)

您想要的数据和标签没有出现在 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]
相关问题