Python 提示 AttributeError: ‘NoneType‘ object has no attribute ‘append‘

Python 提示 AttributeError: 'NoneType' object has no attribute 'append'

1. Scenario recurrence

I wrote a crawler script today, and when I finally integrated the crawled information into a list, it prompted AttributeError: 'NoneType' object has no attribute 'append'

insert image description here

code show as below:

import requests
from lxml import etree
html = requests.get('https://www.cczu.edu.cn/')
html.encoding = "utf-8"
tree = etree.HTML(html.text)
a = tree.xpath("//ul[@class='clearfix']/li")
total = []
for i in a:
    title = ''.join(i.xpath('.//h2//text()'))
    time = ''.join(i.xpath('.//h3//text()'))
    link = ''.join(i.xpath('./h2/a/@href'))
    total = total.append({
    
    'title': title, 'url': link, 'date': time})
print(total)

2. Reason

Debug at the break point, and find that the type of total has changed to NoneType after executing it once. It turns out that append will modify total itself and return None, and the return value cannot be assigned to total.

3. Solve

total = total.append({'title': title, 'url': link, 'date': time})Changing total.append({'title': title, 'url': link, 'date': time})to solve the problem

insert image description here
The correct code is as follows:

import requests
from lxml import etree
html = requests.get('https://www.cczu.edu.cn/')
html.encoding = "utf-8"
tree = etree.HTML(html.text)
a = tree.xpath("//ul[@class='clearfix']/li")
total = []
for i in a:
    title = ''.join(i.xpath('.//h2//text()'))
    time = ''.join(i.xpath('.//h3//text()'))
    link = ''.join(i.xpath('./h2/a/@href'))
    total.append({
    
    'title': title, 'url': link, 'date': time})
print(total)

Guess you like

Origin blog.csdn.net/a6661314/article/details/126736028