目标
- 抓取糗事百科上的段子
- 实现每按一次回车显示一个段子
- 输入想要看的页数,按 'Q' 或者 'q' 退出
实现思路
- 目标网址:糗事百科
- 使用requests抓取页面 requests官方教程
- 使用bs4模块解析页面,获取内容 bs4官方教程
代码内容:
import requests
from bs4 import BeautifulSoup def get_content(pages): # get jokes list
headers = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) Apple\
WebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36'} # 用户代理
content_list = []
for page in range(1, pages+1): # 想看多少页
url = 'http://www.qiushibaike.com/text/page/' + str(page) + '/?s=4928950'
response = requests.get(url, headers=headers) # 获取网页内容
html = response.text
soup = BeautifulSoup(html, 'html5lib') # 解析网页内容
jokes = soup.find_all('div', class_='content')
for each in jokes:
each_joke = each.get_text()
joke = each_joke.replace('\n', '') # 将换行符替换
content_list.append(joke)
return content_list # 返回段子列表 if __name__ == "__main__":
number = int(input("How many pages do you want to read?\nIf you want to quit, just press 'q'.\n")) # 输入想要看的页数
print() # 换行,便于阅读
for paragraph in get_content(number):
print(paragraph)
user_input = input()
if user_input == 'q': # 按'q'退出
break
结果展示:
参考:
http://www.jianshu.com/p/19c846daccb3
静谧的爬虫教程:https://cuiqingcai.com/990.html