|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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
复制代码
本帖最后由 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)
复制代码
|
|