[英]BeautifulSoup Error: TypeError: object of type 'NoneType' has no len()
[英]BeautifulSoup returning a TypeError: object of 'NoneType' has no len()
我正在使用 BeautifulSoup 來抓取數據並返回我列表中所有div
的列表,但它給了我這個錯誤:
Traceback (most recent call last):
File "C:\Users\intel\Desktop\One page\test.py", line 16, in <module>
soup = BeautifulSoup(div.html,'html5lib')
File "C:\Users\intel\AppData\Local\Programs\Python\Python38\lib\site-packages\bs4\__init__.py", line 287, in __init__
elif len(markup) <= 256 and (
TypeError: object of type 'NoneType' has no len()
這是我的代碼:
from bs4 import BeautifulSoup
import requests as req
resp = req.get('https://medium.com/@daranept27')
x = resp.text
soup = BeautifulSoup(x, "lxml")
divs = soup.find_all("div")
#print(divs)
lst = []
for div in divs:
soup = BeautifulSoup(div.html,'html5lib')
div_tag = soup.find()
try:
title = div_tag.section.div.h1.a['href']
if title not in lst: lst.append(title)
except:
pass
print("\n".join(lst))
嘗試使用str(div)
將div
轉換為str
。 這是完整的代碼:
from bs4 import BeautifulSoup
import requests as req
resp = req.get('https://medium.com/@daranept27')
x = resp.text
soup = BeautifulSoup(x, "lxml")
divs = soup.find_all("div")
# print(divs)
lst = []
for div in divs:
soup = BeautifulSoup(str(div), 'html5lib')
div_tag = soup.find()
try:
title = div_tag.section.div.h1.a['href']
if title not in lst: lst.append(title)
except:
pass
print("\n".join(lst))
輸出:
/read-rosy/if-the-whole-world-is-compelled-to-forget-everything-cde200c0ad98
/wordsmith-library/seven-days-between-life-and-death-dffb639fb245
/an-idea/have-you-ever-encountered-a-fake-friend-if-so-try-these-simple-tips-to-overcome-it-d8473d755ab8
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.