python_爬虫一之爬取糗事百科上的段子

目标

  • 抓取糗事百科上的段子
  • 实现每按一次回车显示一个段子
  • 输入想要看的页数,按 'Q' 或者 'q' 退出

实现思路

代码内容:

 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

结果展示:

python_爬虫一之爬取糗事百科上的段子

参考:

Python爬虫实战一之爬取糗事百科段子

http://www.jianshu.com/p/19c846daccb3

静谧的爬虫教程:https://cuiqingcai.com/990.html

爬取段子参考:http://www.jianshu.com/p/0e7d1c80b8c3

上一篇:【Python】【有趣的模块】【requests】【一】HTTP头信息总结


下一篇:TOMcat9 免安装版的配置