我目前正在抓取该网站以构建汽车数据集,并且在抓取时建立了一个方程式循环浏览网站的每个页面。但是,我无法提取完成这项工作所需的文本。
以下代码段是我要抓取的标签。我需要获取站点上的车辆数量。
<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...
[]
为什么给我一个空的清单?
然后,我告诉它打印网站上的每个span标签以查看是否存在。结果打印出许多span标签,但不包括我要查找的标签。为什么我不能用漂亮的汤检测到它?是我使用的解析器吗?我尝试使用“ lxml”作为解析器,但没有任何改变。网站是否为html xmls文档,这与事实有关系吗?
我已经抓了一些网站,到目前为止还没有遇到任何类似的问题。
所需的数据和标记不会出现在html源中,这意味着它们是由javascript添加的。您可以使用selenium在呈现页面后获取页面源,也可以使用request_html,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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句