簡體   English   中英

Python3 beautifulsoup模塊“ NoneType”錯誤

[英]Python3 beautifulsoup module 'NoneType' Error

我是beautifulsoup模塊的新手,但我遇到了問題。 我的代碼很簡單。 畢竟,我要從中刮取的網站是這個,而我要刮除價格。 (第二大(2),其中有更多)

我的代碼:

import urllib
from bs4 import BeautifulSoup


quote_page = 'https://www.bloomberg.com/quote/SPX:IND'

page = urllib.request.urlopen(quote_page)

soup = BeautifulSoup(page, 'html.parser')

price_box = soup.find('div', attr = {'class': 'price'})
price = price_box.text

print(price)

我得到的錯誤:

price = price_box.text

AttributeError: 'NoneType' object has no attribute 'text'

我使用了更強大的CSS選擇器代替了find方法。 由於只有一個帶有class price div元素,我猜這是正確的元素。

import requests
from bs4 import BeautifulSoup

response = requests.get('https://www.bloomberg.com/quote/SPX:IND')
soup = BeautifulSoup(response.content, 'lxml')
price = soup.select_one('.price').text
print(price)

另一個解決方案:

from bs4 import BeautifulSoup
from requests import Session

session = Session()
session.headers['user-agent'] = (
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
    'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'
    '66.0.3359.181 Safari/537.36'
)

quote_page = 'https://www.bloomberg.com/quote/SPX:IND'

page= session.get(quote_page)

soup = BeautifulSoup(page.text, 'html.parser')

price_box = soup.find('meta', itemprop="price")

price = float(price_box['content'])

print(price)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM