MUPING 发表于 2020-11-26 02:42:15

Beautifulsoup抓取网页抓到none可能是哪些原因?

用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


wp231957 发表于 2020-11-26 07:13:45

html是一个变量,没赋值就使用,这肯定是不行的

suchocolate 发表于 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)

MUPING 发表于 2020-11-26 16:08:57

suchocolate 发表于 2020-11-26 10:15
1)去掉:new_html=(html.replace('','')).replace('','')
2)修改解析器:soup = BeautifulSoup(response ...

如果抓取的结果是none,一般可能会是哪些原因呢?
页: [1]
查看完整版本: Beautifulsoup抓取网页抓到none可能是哪些原因?