Python错误:“NoneType”对象没有使用Beautiful Soup的属性“find_all”

2024-10-06 15:27:37 发布

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

我试图运行的一些网页垃圾代码有问题。要从一系列链接中获取信息,请执行以下操作:

http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2006.nsf/ec97fee42a2412d5052578bb001539ee/89045fe8ae896e2e0525751c005544cd?OpenDocument

我试图从表中删除某些元素,但收到以下错误:

Python Error: 'NoneType' object has no attribute 'find_all'

我知道这与它实际上找不到表有关,因为当我运行以下简化代码时:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv
import time

url = 'http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2006.nsf/ec97fee42a2412d5052578bb001539ee/89045fe8ae896e2e0525751c005544cd?OpenDocument'

page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')


table = soup.find('table', {'bordercolor' : '#6583A0'})
print(table)

它为打印的表返回一个“None”,这意味着代码不能删除表的任何特征。我已经为类似的页面运行了类似的代码,并且我能够很好地找到表,所以我不确定为什么这不起作用?我对网络垃圾还不熟悉,但如果有任何帮助,我将不胜感激


Tags: 代码importhttptable垃圾peopendocumentgob
3条回答

import pandas as pd

df = pd.read_html(
    "http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2006.nsf/ec97fee42a2412d5052578bb001539ee/89045fe8ae896e2e0525751c005544cd?OpenDocument")[0]

print(df)
df.to_csv("Data.csv", index=False, header=None)

输出:view online

enter image description here

我认为html包含一些使html解析器无法正确解析html的缺陷,您可以通过打印page.text然后打印soup来验证,您将发现该文档的某些部分已被解析器删除

但是,lxml解析器成功地解析了它,但存在缺陷,因为lxml在格式错误的html文档上更好:

rom bs4 import BeautifulSoup
import requests
import pandas as pd
import csv
import time

url = 'http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2006.nsf/ec97fee42a2412d5052578bb001539ee/89045fe8ae896e2e0525751c005544cd?OpenDocument'

page = requests.get(url)
soup = BeautifulSoup(page.text, 'lxml')


table = soup.find('table', {'bordercolor' : '#6583A0'})
print(table)

应该正确捕捉表标记

因此,soup无法正确解析网站内容,因为一个标记不正确,并破坏了结构。您必须在解析它之前修复它:

url = 'http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2006.nsf/ec97fee42a2412d5052578bb001539ee/89045fe8ae896e2e0525751c005544cd?OpenDocument'

page = requests.get(url)
soup = BeautifulSoup(page.text.replace("</script\n", "</script>"), 'html.parser')

table = soup.find('table', {'bordercolor' : '#6583A0'})
print(table)

相关问题 更多 >