【问题标题】:BeautifulSoup returns None even though the (div = "pendingcasescnts ng-scope") element existsBeautifulSoup 返回 None 即使 (div = "pendingcasescnts ng-scope") 元素存在
【发布时间】:2018-10-30 16:31:37
【问题描述】:

我正在尝试从站点的“Div”multiCLass 中抓取文本:Concluded Cases with Details

The example of the "div" class

找不到div元素?

from bs4 import BeautifulSoup
from requests import get
url ="https://icsid.worldbank.org/en/Pages/cases/ConcludedCases.aspx?status=c"
response = get(url)
html_soup = BeautifulSoup(response.text, 'html.parser')
cases_containers = html_soup.find_all('div', class_ ="pendingcasescnts ng-scope")
print(len(cases_containers))

【问题讨论】:

  • ng-scope 表示 Angular,它是一个 JavaScript 库。该 div 是否存在于HTML 本身中,还是在浏览器中创建?
  • @Chris 我认为“div”存在于 html 本身中,您可以通过检查网站来验证:icsid.worldbank.org/en/Pages/cases/ConcludedCases.aspx?status=c
  • 我通常不会去场外了解您的问题(下一次,请包括所有相关数据,以便您的问题是独立的),但我可以告诉您认为页面的服务器响应 not 包含带有 ng-scope 属性的 <div>。它必须通过 JavaScript 创建,在这种情况下,您应该查看我上面给出的建议副本。 (通过禁用 JavaScript 然后尝试加载页面自己尝试。)
  • 克里斯是对的,你需要selenium

标签: python html python-3.x web-scraping beautifulsoup


【解决方案1】:

您可以观察到页面通过单独的请求请求屏幕上的所有信息,而不是抓取 HTML,该请求以 JSON 格式返回您需要的所有数据。可以使用 .json() requests 函数将其转换为 Python 字典。

下面展示了如何使用返回的 JSON 来提取 Case NoSubjectSector 字段:

from urllib3.exceptions import InsecureRequestWarning
import requests

requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
r = requests.get('https://wbwcfe.worldbank.org/icsidext/service.svc/getbulkcasesbystatusid/json?id=cd28', verify=False)
data = r.json()

for case in data['GetBulkCasesByStatusIdResult']:
    print(f"Case No.: {case['caseno']}\nSubject: {case['subject']}\nSector: {case['econsector']}\n")    

为您提供如下输出案例:

Case No.: CONC/18/1
Subject: Water services and electric power concession
Sector: Electric Power & Other Energy

Case No.: ARB/17/40
Subject: Hydrocarbon concession
Sector: Oil, Gas & Mining

Case No.: ARB/17/39
Subject: Hydrocarbon concession
Sector: Oil, Gas & Mining

在加载问题中给出的 URL 时,使用浏览器的网络工具找到了该 URL。

我建议您打印出data 并研究所有可用的字段。

【讨论】:

  • 谢谢马丁,我对 selenium 有相同的结果,但你的解决方案更优化
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2021-05-26
  • 2019-11-27
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多