![](/img/trans.png)
[英]AttributeError: 'NoneType' object has no attribute 'get_text' python web-scraping
[英]AttributeError: 'NoneType' object has no attribute 'get_text' in beautifulsoop web-scraping
我正在做一個在 python 中使用 beautifulsoop(web scraping) 的項目。 早些時候,該程序運行良好且完美。 但是,現在它給出了如下所示的錯誤。 可能是網站的 html 結構會發生變化。 但我仍然無法找出錯誤並解決它。 請幫忙!!!
該網站是 - [https://covidindia.org/][1]
請幫我解決錯誤。
錯誤-
Traceback (most recent call last):
File "t1.py", line 112, in <module>
mainLabel = tk.Label(root, text=get_corona_detail_of_india(), font=f, bg='light blue',fg='red')
File "t1.py", line 23, in get_corona_detail_of_india
total_cases = soup.find("div",class_="elementor-element elementor-element-aceece0 elementor-widget elementor-widget-heading",).get_text()
AttributeError: 'NoneType' object has no attribute 'get_text
我的代碼-
URL = 'https://covidindia.org/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
#print(soup)
total_cases = soup.find("div",class_="elementor-element elementor-element-aceece0 elementor-widget elementor-widget-heading",).get_text()
tc=(total_cases.strip())
同樣,當我提取湯時,o/p 是-
<html><head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr/><center>nginx</center>
我的訪問是永久禁止的嗎??
向您的請求添加user-agent
標頭。 當您不添加user-agent
,網站會將您檢測為機器人,因此不會讓您訪問網站的內容。 這是完整的代碼:
from bs4 import BeautifulSoup
import requests
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0'}
URL = 'https://covidindia.org/'
page = requests.get(URL,headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
#print(soup)
total_cases = soup.find("div",class_="elementor-element elementor-element-aceece0 elementor-widget elementor-widget-heading",).get_text()
tc=(total_cases.strip())
輸出:
>>> tc
'Total Cases - 83,14,673 (+46,171)'
當站點需要一個您沒有放入請求中的對象時,會發生此問題,檢查站點需要什么,它可能是其他用戶回答的用戶代理或其他一些東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.