import requests from bs4 import BeautifulSoup url = 'https://weibo.com/u/1670659923' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' } cookies = { 'Cookie': '1mN2r5kExwviijjaUAMJq3Ks' } response = requests.get(url, headers=headers, cookies=cookies) soup = BeautifulSoup(response.text, 'html.parser') #获取名称 name = soup.find('div', {'class': 'detail_wbtext_4CRf9'}).text print(name) 执行以上代码报以下错误name = soup.find('div', {'class': 'detail_wbtext_4CRf9'}).text AttributeError: 'NoneType' object has no attribute 'text' 请根据报错修改代码
时间: 2023-10-01 18:11:36 浏览: 172
该错误表示无法找到相应的 div 标签,导致 `soup.find()` 方法返回了 `None`。可能是因为网页的结构发生了变化,或者定位 div 标签的 class 名称不正确。可以尝试修改为以下代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://weibo.com/u/1670659923'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
cookies = {
'Cookie': '1mN2r5kExwviijjaUAMJq3Ks'
}
response = requests.get(url, headers=headers, cookies=cookies)
soup = BeautifulSoup(response.text, 'html.parser')
# 修改为通过标签名获取 div 标签内的文本内容
name = soup.find('div', {'class': 'pf_username'}).find('a').text
print(name)
```
这段代码将通过标签名获取 `pf_username` class 下的 a 标签内的文本内容,避免了直接获取 `detail_wbtext_4CRf9` class 下的 div 标签的问题。
阅读全文