import requests
import time
from bs4 import BeautifulSoup
# 首先我们写好抓取网页的函数
url = "http://tieba.baidu.com/f?kw=%E7%94%9F%E6%B4%BB%E5%A4%A7%E7%88%86%E7%82%B8&ie=utf-8"
def get_html(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
# 这里我们知道百度贴吧的编码是utf-8,所以手动设置的。爬去其他的页面时建议使用:
#r.endcodding = r.apparent_encoding()
r.encoding = 'utf-8'
return r.text
except:
return " ERROR "
def get_content(url):
# 初始化一个列表来保存所有的帖子信息:
comments = []
# 首先,我们把需要爬取信息的网页下载到本地
html = get_html(url)
# 我们来做一锅汤
soup = BeautifulSoup(html, 'html.parser')
# 按照之前的分析,我们找到所有具有‘ j_thread_list clearfix’属性的li标签。返回一个列表类型。
liTags = soup.find_all('li', class_ ="j_thread_list clearfix")
for li in liTags:
# 初始化一个字典来存储文章信息
comment = {}
# 这里使用一个try except 防止爬虫找不到信息从而停止运行
try:
comment['title'] = li.find(
'a', attrs={'class': 'j_th_tit'}).text.strip()
comment['link'] = "http://tieba.baidu.com"+ \
li.find('a', attrs={'class': 'j_th_tit'})['href']
comment['name'] = li.find(
'span', attrs={'class': 'frs-author-name-wrap'}).text.strip()
comment['time'] = li.find(
'span', attrs={'class': 'pull-right is_show_create_time'}).text.strip()
comment['replyNum'] = li.find(
'span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
comments.append(comment)
except:
print('出了点小问题')
return comments
print (get_content(url))
soup.find_all(class_="")
class后面字符串的处理过程中需要注意特殊字符的处理,虽然原网页代码中存在空格,但是匹配过程中写入空格无法获取内容信息,具体细节还需进一步学习。