Python attributeerror nonetype object has no attribute text

‘NoneType’ object has no attribute ‘text’ in TableWidgets

I was trying to work with TableWidgets on Python and I ran into an issue. I wanted to check whether the table is filled or not (with str of course).

def add_table (self): self.kala = self.comboBox.currentText() self.code_kala = self.comboBox.currentIndex() self.vahed = self.comboBox_2.currentText() list_e = [] for i in list(range(10)): #self.tab = self.tableWidget.item(i,0) if self.tableWidget.item(i,0).text() != '': #if self.tab.text() !='': list_e.append(i) else: pass self.ROW = len(list_e) self.tableWidget.setItem(self.ROW,0,QTableWidgetItem(self.kala)) self.tableWidget.setItem(self.ROW,1,QTableWidgetItem(str(self.code_kala))) self.tableWidget.setItem(self.ROW,2,QTableWidgetItem(str(self.vahed))) 

and I don’t know why I keep getting this error: NoneType’ object has no attribute ‘text’ Does anyone know how to solve it? Also, I know this code doesn’t have any problem (I got good results with the same code in another project) but as cmd said:

File "D:\**\***\*****\*******\*\*************.py", line 1755, in add_table if self.tableWidget.item(i,0).text() != '': AttributeError: 'NoneType' object has no attribute 'text' 

NoneType Means the variable has nothing in it. You could use a debugger to check why the variable is empty.

You could print the object just before the conditional statement and that should give you a clue which item is missing. Or you could Catch the error and inspect/print relevant data in the except suite. One of your table items is empty: if you expect to have empty cells(?) catch the error and pass in the except suite.

As an aside: you can iterate over a range object without making a list from it : for i in list(range(10)): —>> for i in range(10): . And I was looking through some SO Q&A’s like this one — seems that Qtables (?) have a rowCount() method so the for statement becomes — for i in self.tableWidget.rowCount() .

@wwii ty man i found my problem with Your solution i used print function and i got None after 10 times ‘ ‘ so i changed the range(10) to range(9) and solved it

Источник

Object Has No Attribute ‘Text’

Ok, let’s try this again. I am scraping a webpage that is in xml format. I am gathering what I need, but for one item it is unable to pull the text (dubbed ‘item’ in my code below). I am getting the following error: «item = items.find(«image:title»).text AttributeError: ‘NoneType’ object has no attribute ‘text'» I would just like to get the text for ‘item’. Here’s my code:

import requests from bs4 import BeautifulSoup headers = url = 'https://www.kith.com/sitemap_products_1.xml' r = requests.get(url=url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') for items in soup.find_all("url"): item = items.find("image:title").text url = items.find("loc").text if item is not None: print(item, url) 

2 Answers 2

Your first text return None so you get this error . You need to check item is none or not before trying to get text.

for items in soup.find_all("url"): getTitle = items.find('image:title') if getTitle is not None: item = getTitle.text url = items.find("loc").text print (item,url) 
item = items.find("image:title").text 

items.find(«image:title») return None (probably because find does not find what you expect in items ). So then as None does not have the attribute text then (None).text raises the error AttributeError: ‘NoneType’ object has no attribute ‘text’

Читайте также:  Java string replace all whitespaces

If you want to fix the error, you can do:

item = items.find("image:title") if item: title = item.text # you can use other variable name if you want to. else: print("there is no image:title in items") 

Источник

Python XML AttributeError: ‘NoneType’ object has no attribute ‘text’

I am new to Python but created the script below to import the XML file above and that is when I receive the error above. Below is my code.

import xml.etree.ElementTree as ET myfile = 'C:/Users/user1/Desktop/file.xml' tree = ET.parse(myfile) root = tree.getroot() for x in root.findall('blue'): animal = x.find('animal').text key1 = x.attrib['key'] state = x.find('state').text zoo = x.find('zoo').text year = x.find('year').text print animal, key1, state, zoo, year for y in root.findall('red'): elem_a = y.find('elem_a').text key2 = y.attrib['key'] elem_b = y.find('elem_b').text elem_c = y.find('elem_c').text elem_d = y.find('elem_d').text print elem_a, key2, elem_b, elem_c, elem_d for z in root.findall('yellow'): car = z.find('car').text key3 = z.attrib['key'] cap = z.find('cap').text cat = z.find('cat').text print car, key3, cap, cat 

In the XML file there are three main element types: blue, red and yellow. One of the problems specific child elements exist for some parent elements are not for others. For example, in the sample XML file above, one «yellow» element has three child elements including «car», «cat» and «cap» but not each «yellow» element has all three child elements. In the XML below the first «yellow» element has the «cat» child node and the second «yellow» element does not have the «cat» child element but in the full XML file the «yellow» elements could have any one, two or three of the «cat», «cap» and «car» child elements. I know this is causing the error but I do not know how to resolve it. Does anyone have any ideas or tips as to how to resolve this error? Thank you.

Источник

BeautifulSoup «AttributeError: ‘NoneType’ object has no attribute ‘text'» [duplicate]

I was web-scraping weather-searched Google with bs4, and Python can’t find a tag when there is one. How can I solve this problem? I tried to find this with the class and the id , but both failed.

 
Clear with periodic clouds
response = requests.get('https://www.google.com/search?hl=ja&ei=coGHXPWEIouUr7wPo9ixoAg&q=%EC%9D%BC%EB%B3%B8+%E6%A1%9C%E5%B7%9D%E5%B8%82%E7%9C%9F%E5%A3%81%E7%94%BA%E5%8F%A4%E5%9F%8E+%EB%82%B4%EC%9D%BC+%EB%82%A0%EC%94%A8&oq=%EC%9D%BC%EB%B3%B8+%E6%A1%9C%E5%B7%9D%E5%B8%82%E7%9C%9F%E5%A3%81%E7%94%BA%E5%8F%A4%E5%9F%8E+%EB%82%B4%EC%9D%BC+%EB%82%A0%EC%94%A8&gs_l=psy-ab.3. 232674.234409..234575. 0.0..0.251.929.0j6j1. 0. 1..gws-wiz. 35i39.yu0YE6lnCms') soup = BeautifulSoup(response.content, 'html.parser') tomorrow_weather = soup.find('span', ).text 
Traceback (most recent call last): File "C:\Users\sungn_000\Desktop\weather.py", line 23, in tomorrow_weather = soup.find('span', ).text AttributeError: 'NoneType' object has no attribute 'text' 

Doesn’t work for me either with chrome. Is it supposed to get an actual page or just the search results? That id is not present when I inspect.

Читайте также:  Php while loop and array

4 Answers 4

This is because the weather section is rendered by the browser via JavaScript. So when you use requests you only get the HTML content of the page which doesn’t have what you need. You should use for example selenium (or requests-html ) if you want to parse page with elements rendered by web browser.

from bs4 import BeautifulSoup from requests_html import HTMLSession session = HTMLSession() response = session.get('https://www.google.com/search?hl=en&ei=coGHXPWEIouUr7wPo9ixoAg&q=%EC%9D%BC%EB%B3%B8%20%E6%A1%9C%E5%B7%9D%E5%B8%82%E7%9C%9F%E5%A3%81%E7%94%BA%E5%8F%A4%E5%9F%8E%20%EB%82%B4%EC%9D%BC%20%EB%82%A0%EC%94%A8&oq=%EC%9D%BC%EB%B3%B8%20%E6%A1%9C%E5%B7%9D%E5%B8%82%E7%9C%9F%E5%A3%81%E7%94%BA%E5%8F%A4%E5%9F%8E%20%EB%82%B4%EC%9D%BC%20%EB%82%A0%EC%94%A8&gs_l=psy-ab.3. 232674.234409..234575. 0.0..0.251.929.0j6j1. 0. 1..gws-wiz. 35i39.yu0YE6lnCms') soup = BeautifulSoup(response.content, 'html.parser') tomorrow_weather = soup.find('span', ).text print(tomorrow_weather) 
pawel@pawel-XPS-15-9570:~$ python test.py Clear with periodic clouds 
>>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(a) >>> a '
\n Clear with periodic clouds \n
' >>> soup.find("span", ).text 'Clear with periodic clouds'

If you inspect the response.content of request.get you won’t find span in the content. It is because Javascript rendering the HTML and you don’t get what you intending.

It’s not rendered via JavaScript as pawelbylina mentioned, and you don’t have to use requests-html or selenium since everything needed is in the HTML, and it will slow down the scraping process a lot because of page rendering.

It could be because there’s no user-agent specified thus Google blocks your request and you receiving a different HTML with some sort of error because the default requests user-agent is python-requests. Google understands it and blocks a request since it’s not the «real» user visit. Checks what’s your user-agent .

Pass user-agent intro request headers:

headers = < "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" >requests.get("YOUR_URL", headers=headers) 

You’re looking for this, use select_one() to grab just one element:

Have a look at SelectorGadget Chrome extension to grab CSS selectors by clicking on the desired elements in your browser.

from bs4 import BeautifulSoup import requests, lxml headers = < "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" >params = < "q": "일본 桜川市真壁町古城 내일 날씨", "hl": "en", >response = requests.get('https://www.google.com/search', headers=headers, params=params) soup = BeautifulSoup(response.text, 'lxml') location = soup.select_one('#wob_loc').text weather_condition = soup.select_one('#wob_dc').text tempature = soup.select_one('#wob_tm').text precipitation = soup.select_one('#wob_pp').text humidity = soup.select_one('#wob_hm').text wind = soup.select_one('#wob_ws').text current_time = soup.select_one('#wob_dts').text print(f'Location: \n' f'Weather condition: \n' f'Temperature: °F\n' f'Precipitation: \n' f'Humidity: \n' f'Wind speed: \n' f'Current time: \n') ------ ''' Location: Makabecho Furushiro, Sakuragawa, Ibaraki, Japan Weather condition: Cloudy Temperature: 79°F Precipitation: 40% Humidity: 81% Wind speed: 7 mph Current time: Saturday ''' 

Alternatively, you can achieve the same thing by using the Direct Answer Box API from SerpApi. It’s a paid API with a free plan.

Читайте также:  List index python примеры

The difference in your case is that you don’t have to think about how to bypass block from Google or figure out why data from certain elements aren’t extracting as it should since it’s already done for the end-user. The only thing that needs to be done is to iterate over structured JSON and grab the data you want.

from serpapi import GoogleSearch import os params = < "engine": "google", "q": "일본 桜川市真壁町古城 내일 날씨", "api_key": os.getenv("API_KEY"), "hl": "en", >search = GoogleSearch(params) results = search.get_dict() loc = results['answer_box']['location'] weather_date = results['answer_box']['date'] weather = results['answer_box']['weather'] temp = results['answer_box']['temperature'] precipitation = results['answer_box']['precipitation'] humidity = results['answer_box']['humidity'] wind = results['answer_box']['wind'] print(f'\n\n\n°F\n\n\n\n') -------- ''' Makabecho Furushiro, Sakuragawa, Ibaraki, Japan Saturday Cloudy 79°F 40% 81% 7 mph ''' 

Источник

AttributeError: ‘NoneType’ Object Has No Attribute ‘Text’ in Python

AttributeError:

This error happens when you try to call a method from an object that is None or not initiated. Before calling a method, you need to check if the object is None or not to eliminate this error; after that, call the desired method.

AttributeError is an exception you get while you call the attribute, but it is not supported or present in the class definition.

Causes and Solutions of the AttributeError: ‘NoneType’ object has no attribute ‘text’ in Python

This error is common while you’re doing web scraping or XML parsing. During the parsing, you’ll get this error if you get unstructured data.

  1. Data that JavaScript dynamically rendered.
  2. Scraping multiple pages with the same data.
  3. While parsing XML, if the node you are searching is not present.
  1. Check if the element exists before calling any attribute of it.
  2. Check the response to the request.

an Example Code

As this error often comes from web scraping, let’s see an example of web scraping. We will try to get the title of the StackOverflow website with our Python script.

from bs4 import BeautifulSoup as bs import requests url = "https://www.stackoverflow.com/"  html_content = requests.get(url).text soup = bs(html_content, "html.parser")  if soup.find('title').text is not None:  print(soup.find('title').text) 
Stack Overflow - Where Developers Learn, Share, & Build Careers 

Here, you will notice that the if condition we used is is not None to ensure we’re calling an existing method. Now, it will not show any error such as the AttributeError .

I’m Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I’m working with two companies as a part-time backend engineer.

Related Article — Python Error

Related Article — Python AttributeError

Copyright © 2023. All right reserved

Источник

Оцените статью