|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import requests
import bs4
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'}
res = requests.get('https://tieba.baidu.com/f?ie=utf-8&kw=%E5%B7%B4%E5%A1%9E%E7%BD%97%E9%82%A3&fr=search', headers = headers)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
targets = soup.find_all("div", class_="threadlist_title threadlist_title j_th_tit")
for each in targets:
with open("baidu.txt", "w", encoding="utf-8") as file:
file.write(each.i.a.text)
想爬百度贴吧的标题,为什么没有这个文件呢
本帖最后由 YunGuo 于 2020-12-20 20:23 编辑
百度中源代码是被注释的,你这样直接肯定是获取不到,需要先把注释符号替换掉。
- html = res.text.replace('<!--', '').replace('-->', '')
复制代码
另外你确定这个class threadlist_title threadlist_title j_th_tit是存在的?我看了下class应该是这个
- targets = soup.find_all("div", class_="threadlist_title pull_left j_th_tit")
复制代码
最后each.i.a.text,这个错了,置顶帖中的i标签和a标签是兄弟关系,不是父子关系。如果你想获取页面所有帖子的标题,应该这样写
修改后
- import requests
- from bs4 import BeautifulSoup
- headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
- '(KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
- }
- url = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E5%B7%B4%E5%A1%9E%E7%BD%97%E9%82%A3&fr=search'
- res = requests.get(url, headers=headers)
- html = res.text.replace('<!--', '').replace('-->', '')
- soup = BeautifulSoup(html, 'html.parser')
- targets = soup.find_all('div', class_="threadlist_title pull_left j_th_tit")
- with open('baidu.text', 'w', encoding='utf-8') as f:
- for each in targets:
- f.write(each.a.text)
- f.write('\n')
复制代码
|
|