【发布时间】:2021-05-23 07:15:57
【问题描述】:
我正在尝试从以下 URL 中刮取财务数据:https://www.londonstockexchange.com/stock/STAN/standard-chartered-plc/fundamentals
在这个网页中,通过引用它的类来抓取h1 标签可以完美地工作。
源 HTML:
<h1 _ngcontent-ng-lseg-c11="" class="company-name font-bold hero-font"><!----><!---->STANDARD CHARTERED PLC<!----><!----><!----></h1>
我的 Python 代码:
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
url = 'https://www.londonstockexchange.com/stock/{}/{}'
stock = 'STAN/standard-chartered-plc'
info = 'fundamentals'
full_url = url.format(stock, info)
print(full_url)
r = requests.get(full_url)
soup = BeautifulSoup(r.text, 'lxml')
title = soup.find('title')
print(title)
rows = soup.find(class_='company-name font-bold hero-font')
print(rows)
输出:
https://www.londonstockexchange.com/stock/STAN/standard-chartered-plc/fundamentals
<title>STANDARD CHARTERED PLC STAN Fundamentals - Stock | London Stock Exchange</title>
<h1 _ngcontent-sc12="" class="company-name font-bold hero-font"><!-- --><!-- -->STANDARD CHARTERED PLC<!-- --><!-- --><!-- --></h1>
但是当试图抓取网页的另一部分,即以下标签时,此功能停止工作:
<thead _ngcontent-ng-lseg-c21="" class="accordion-header gtm-trackable">
我的 Python 代码:
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
url = 'https://www.londonstockexchange.com/stock/{}/{}'
stock = 'STAN/standard-chartered-plc'
info = 'fundamentals'
full_url = url.format(stock, info)
print(full_url)
r = requests.get(full_url)
soup = BeautifulSoup(r.text, 'lxml')
title = soup.find('title')
print(title)
rows = soup.find(class_='accordion-header gtm-trackable')
print(rows)
我的输出如下:
https://www.londonstockexchange.com/stock/STAN/standard-chartered-plc/fundamentals
<title>STANDARD CHARTERED PLC STAN Fundamentals - Stock | London Stock Exchange</title>
None
我试过使用 'html.parser' 和 'lxml' 都导致同样的问题。
【问题讨论】:
标签: python html web-scraping beautifulsoup