鱼C论坛

 找回密码
 立即注册
查看: 1729|回复: 3

[已解决]Beautifulsoup抓取网页抓到none可能是哪些原因?

[复制链接]
发表于 2020-11-26 02:42:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
用Beautifulsoup抓取网页抓到none,试了把<br>标签替换掉了,但是报错中说替换的代码中HTML name不准确,不知道怎么修正,求教代码:
import requests
from bs4 import BeautifulSoup
response = requests.get('https://tieba.baidu.com/p/959866703?pn=1')
new_html=(html.replace('<br>','')).replace('<br/>','')
soup = BeautifulSoup(response.text,'new_html.parser')
content = soup.find('div',{'id:j_p_postlist'})
print(content)
============== RESTART: C:/Users/user/Desktop/数据新闻/第三次python作业.py ==============
Traceback (most recent call last):
  File "C:/Users/user/Desktop/数据新闻/第三次python作业.py", line 4, in <module>
    new_html=(html.replace('<br>','')).replace('<br/>','')
NameError: name 'html' is not defined


最佳答案
2020-11-26 10:15:25
本帖最后由 suchocolate 于 2020-11-26 11:11 编辑

1)去掉:new_html=(html.replace('<br>','')).replace('<br/>','')
2)修改解析器:soup = BeautifulSoup(response.text,'html.parser') # 第二个参数是soup支持的4个固定的解析器的名称,不是用户能自定义的变量,其他还有:lxml,xml,html5lib。
3)find里属性变成字典,不是字符串:content = soup.find('div', {'id': 'j_p_postlist'})
import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla'}
response = requests.get('https://tieba.baidu.com/p/959866703?pn=1', headers=headers)  # 养成改ua的好习惯
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', attrs={'id': 'j_p_postlist'})    # 规范写法属性要加attrs=
print(content)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-11-26 07:13:45 From FishC Mobile | 显示全部楼层
html是一个变量,没赋值就使用,这肯定是不行的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-11-26 10:15:25 | 显示全部楼层    本楼为最佳答案   
本帖最后由 suchocolate 于 2020-11-26 11:11 编辑

1)去掉:new_html=(html.replace('<br>','')).replace('<br/>','')
2)修改解析器:soup = BeautifulSoup(response.text,'html.parser') # 第二个参数是soup支持的4个固定的解析器的名称,不是用户能自定义的变量,其他还有:lxml,xml,html5lib。
3)find里属性变成字典,不是字符串:content = soup.find('div', {'id': 'j_p_postlist'})
import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla'}
response = requests.get('https://tieba.baidu.com/p/959866703?pn=1', headers=headers)  # 养成改ua的好习惯
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', attrs={'id': 'j_p_postlist'})    # 规范写法属性要加attrs=
print(content)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-11-26 16:08:57 | 显示全部楼层
suchocolate 发表于 2020-11-26 10:15
1)去掉:new_html=(html.replace('','')).replace('','')
2)修改解析器:soup = BeautifulSoup(response ...

如果抓取的结果是none,一般可能会是哪些原因呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-11 12:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表