首页 > 解决方案 > 网页抓取/Beautifulsoup/有时无回报?

问题描述

我尝试从网页上抓取一些信息,在一个页面上它工作正常,但在另一个网页上它不起作用,因为我只得到一个无返回值

此代码/网页运行良好:

# https://realpython.com/beautiful-soup-web-scraper-python/
import requests
from bs4 import BeautifulSoup

URL = "https://www.monster.at/jobs/suche/?q=Software-Devel&where=Graz"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")

name_box = soup.findAll("div", attrs={"class": "company"})
print (name_box)

但是使用此代码/网页,我只能得到一个 None 作为返回值

# https://www.freecodecamp.org/news/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe/

import requests
from bs4 import BeautifulSoup

URL = "https://www.bloomberg.com/quote/SPX:IND"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")


name_box = soup.find("h1", attrs={"class": "companyName__99a4824b"})
print (name_box)

这是为什么?

(起初我认为由于第二个网页“companyName__99a4824b”上的类中的数字,它会动态更改类名 - 但事实并非如此 - 当我刷新网页时,它仍然是相同的类名......)

标签: pythonweb-scrapingbeautifulsoup

解决方案


您得到的原因None是彭博页面使用 Javascript 在用户在页面上时加载其内容。

BeautifulSoup只需在页面到达页面后立即将页面的 html 返回给您,该页面不包含companyName_99a4824b类标签。

只有在用户等待页面完全加载后,html 才会包含所需的标签。

如果你想抓取这些数据,你需要使用像Selenium这样的东西,你可以指示它等到页面的所需元素准备好。


推荐阅读