[英]Error bs4: find_all | development vs production
在我的開發機器 (localhost) 中運行以下代碼時我沒有遇到任何問題:
headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"}
exampleFile = requests.get(f'https://statusinvest.com.br/acoes/petr4',headers=headers)
exampleSoup = bs4.BeautifulSoup(exampleFile.text, features="html.parser")
container_indicadores = exampleSoup.find('div', {'class': "indicator-today-container"}).find_all('div', {'title': True})
但是,我剛剛推送到鐵路服務器(生產),現在它出現了錯誤:
'NoneType' object has no attribute 'find_all'
我的目標是抓住所有在title內有任何內容並且在div div class="indicator-today-container"
內的 div
信息:
python 版本幾乎相同:production 3.10.8 | 本地主機:3.10.1
bs4 的要求為 4.11.1 - 我假設生產和本地主機之間沒有區別
Windows 操作系統在我的本地主機中,我假設 Linux 是@鐵路服務器
任何的想法?
編輯:
我添加了 02 個變量來找出錯誤:
example = exampleFile.text
first = exampleSoup.find('div', {'class': "indicator-today-container"})
價值觀:
example = ('<!DOCTYPE html>\n'
'<html lang="en-US">\n'
'<head>\n'
' <title>Just a moment...</title>\n'
' <meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">\n'
' <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n'
' <meta name="robots" content="noindex,nofollow">\n'
' <meta name="viewport" content="width=device-width,initial-
scale=1">\n'
' <link href="/cdn-cgi/styles/challenges.css"
rel="stylesheet">\n'
' \n'
'\n'
'</head>\n'...)
但第一個變量是None
我的目標是抓住所有在title內有任何內容並且在div
div class="indicator-today-container"
內的 div
為了避免在這些情況下引發此類錯誤,最好避免鏈接.find
,而是使用.select
和CSS 選擇器。
container_indicadores = exampleSoup.select('div.indicator-today-container div[title]')
這樣,即使您沒有找到任何東西,您最終也會得到一個空列表,但不會引發任何錯誤。
'NoneType' object has no attribute 'find_all'
但第一個變量是
None
[所以你的第一個片段的最后一行基本上等同於container_indicadores = None.find_all('div', {'title': True})
和 ofc 會引發錯誤。]你應該檢查你的請求是否成功
exampleFile = requests.get(f'https://statusinvest.com.br/acoes/petr4',headers=headers)
print(exampleFile.status_code, exampleFile.reason, 'from', exampleFile.url)
對我來說,打印403 Forbidden from https://statusinvest.com.br/acoes/petr4
(如果我嘗試使用cloudscraper ,它會引發CloudflareChallengeError
異常 - Detected a Cloudflare version 2 Captcha challenge...
,所以他們似乎有非常好的反機器人攔截器。)
example = exampleFile.text
價值觀:
通常,如果您改為查看exampleSoup.get_text()
,則更容易發現問題:
這是我使用 ScrapingAnt時得到的屏幕截圖 [我希望selenium 得到類似的結果]。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.