【问题标题】:Unable to extract text from a specific span tag using Python's Beautiful Soup无法使用 Python 的 Beautiful Soup 从特定的 span 标签中提取文本
【发布时间】:2021-02-06 00:34:07
【问题描述】:

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

下面的代码 sn-p 是我要抓取的标签。我需要获取站点上的车辆数量。

<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这一事实有关吗?

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

【问题讨论】:

  • 总计数元素很可能是由一些 javascript 填充的。所以它实际上并没有暴露在请求返回的html中。

标签: python html xml beautifulsoup


【解决方案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]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2013-05-20
  • 2020-07-04
  • 2017-12-31
  • 2017-05-27
  • 1970-01-01
相关资源
最近更新 更多