AttributeError:“非类型”对象在beautifulsoop webscraping中没有属性“get_text”

2024-04-27 02:52:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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>

我的访问是否永久禁止??


Tags: texthttpsorgget网站html错误element
2条回答

当站点需要一个您没有放入请求中的对象时,就会出现此问题,请检查站点需要什么,它可能是其他用户应答时的用户代理,或者是其他什么东西

在请求中添加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)'

相关问题 更多 >