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/114.0.0.0 Safari/537.36 Edg/114.0.1823.41' } cookies = { 'SUB': '_2A25JhpdQDeRhGeBM61MQ8CjOzzqIHXVq9Y-YrDV8PUNbmtAGLWvxkW9NRQ-ugE6rVY1cMvmezl4YyGeJ1ClvO4dN', 'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9Wh2o78rH.vjBjZo6khos3mY5JpX5KzhUgL.FoqEeh2pehqEShq2dJLoIpjLxK.L1h2LB--LxKBLBonL12BLxKnL1hzL1h.t;' 'ALF=1717836416; SSOLoginState=1686300416;_s_tentry=weibo.com;MLOGIN=1;XSRF-TOKEN=LdwKRX-Gczu2_lX9TQQ4O9EY' } response = requests.get(url, headers=headers,cookies=cookies) soup = BeautifulSoup(response.text, 'html.parser') #获取名称 name = soup.find('div', {'class': 'detail_wbtext_4CRf9'}) print(name)为什么打印为none,请修改代码
时间: 2024-01-15 14:04:09 浏览: 168
import sys import os import urllib from bs4 import BeautifulSoup
可能是因为没有找到对应的标签,您可以尝试修改代码,查看是否可以成功获取名称:
```
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/114.0.0.0 Safari/537.36 Edg/114.0.1823.41'
}
cookies = {
'SUB': '_2A25JhpdQDeRhGeBM61MQ8CjOzzqIHXVq9Y-YrDV8PUNbmtAGLWvxkW9NRQ-ugE6rVY1cMvmezl4YyGeJ1ClvO4dN',
'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9Wh2o78rH.vjBjZo6khos3mY5JpX5KzhUgL.FoqEeh2pehqEShq2dJLoIpjLxK.L1h2LB--LxKBLBonL12BLxKnL1hzL1h.t;'
'ALF=1717836416; SSOLoginState=1686300416;_s_tentry=weibo.com;MLOGIN=1;XSRF-TOKEN=LdwKRX-Gczu2_lX9TQQ4O9EY'
}
response = requests.get(url, headers=headers,cookies=cookies)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取名称
name = soup.find('h1', {'class': 'username'})
if name:
print(name.text.strip())
else:
print("未找到对应的标签!")
```
在这里,我将查找的标签从`div`改为了`h1`,并且将该标签的class从`detail_wbtext_4CRf9`改为了`username`,这是因为可能页面的结构或者样式发生了改变。同时,我添加了一个判断语句,如果没有找到对应的标签,则输出一个提示信息。
阅读全文