BeautifulSoup库find()返回列表为None
import requestsfrom bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/76.0.3809.100 Safari/537.36'
}
# 这里是想查的CSDN的备案信息
res = requests.get('https://icp.aizhan.com/www.csdn.net/', headers = headers)
# 异常处理
try:
# 对返回结果进行解析
soup = BeautifulSoup(res.text, 'html.parser')
# 通过find_all()获取主办单位名称
div = soup.find('div', attrs = {'id':'icp-table'})
td_list = div.find_all('td')
name_info = td_list.text + ":" + td_list.text
print(name_info)
# 通过selector获取备案号
icp_no = soup.select('#icp-table > table > tr:nth-of-type(3) > td:nth-of-type(2) > span').get_text()
print(icp_no)
except ConnectionError:
print("连接失败")
我想把网站上的指定信息爬下来,但是报错说div为None,但我检查了一下网页上面的确是有这个元素的,请问是什么原因呢?
这个url需要登陆才能出现你要的div。登陆的话可以直接用登陆点击时提交的cookie。 import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/76.0.3809.100 Safari/537.36'
"cookie":"将浏览器的cookie替换这里的文字"}
# 这里是想查的CSDN的备案信息
res = requests.get('https://icp.aizhan.com/www.csdn.net/', headers = headers)
# 异常处理
try:
# 对返回结果进行解析
soup = BeautifulSoup(res.text, 'html.parser')
# 通过find_all()获取主办单位名称
div = soup.find('div', attrs = {'id':'icp-table'})
td_list = div.find_all('td')
name_info = td_list.text + ":" + td_list.text
print(name_info)
# 通过selector获取备案号
icp_no = soup.select('#icp-table > table > tr:nth-of-type(3) > td:nth-of-type(2) > span').get_text()
print(icp_no)
except ConnectionError:
print("连接失败")
suchocolate 发表于 2021-8-14 14:02
这个url需要登陆才能出现你要的div。登陆的话可以直接用登陆点击时提交的cookie。
感谢! nahongyan1997 发表于 2021-8-14 15:30
感谢!
页:
[1]