Python爬虫 object has no attribute ‘title’ 问题解决

在Python爬虫学习中遇到一个错误:object has no attribute 'title'。问题出在尝试获取title信息时,变量head被识别为NoneType。通过检查,发现`html.read()`返回的是bytes类型,而BeautifulSoup需要的是文本字符串。解决方案是将BeautifulSoup的参数改为`html_text`,从而成功解析网页标题。
摘要由CSDN通过智能技术生成

Python爬虫 object has no attribute ‘title’ 问题解决

在学习python爬虫时,想要获取title信息,遇到object has no attribute ‘title’ 的问题,仔细看并没有标点和拼写错误

原代码


from urllib.request import urlopen
from bs4 import BeautifulSoup as bf

html=urlopen("http://www.baidu.com/")
obj=bf(html.read() ,'html.parser')
title = obj.head.title
print('---------------------------------------------------')
print(title)


输出如下:
在这里插入图片描述

解决

发现此时head为NoneType,尝试输出html.read()的类型:为bytes
在这里插入图片描述

而BeautifulSoup的第一个参数为将要解析的文本字符串,因此修改BeautifulSoup函数的第一个参数为

'list' object has no attribute 'title' 这个报错是因为你尝试在一个列表对象上调用'title'属性,而列表对象并没有'title'属性。可以看出这个问题出现在你的代码中的obj变量上。在你的代码中,你使用了BeautifulSoup库来解析网页内容,但是你在调用BeautifulSoup的时候,传入的是列表对象而不是字符串对象。所以在创建BeautifulSoup对象时,你需要传入一个字符串对象而不是一个列表对象。你可以将urlopen函数获取的网页内容先转换成字符串,然后再传入BeautifulSoup函数进行解析。可以使用bytes.decode()函数将网页内容转换成字符串,然后将转换后的字符串作为第一个参数传入BeautifulSoup函数。这样就可以避免出现'list' object has no attribute 'title'的报错了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [AttributeError: ‘listobject has no attribute ‘to_excel](https://blog.csdn.net/ml7yuwanhanhua/article/details/127295497)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python爬虫 object has no attributetitle问题解决](https://blog.csdn.net/weixin_44038564/article/details/121075295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值