python爬虫之爬取笑话(二)
爬取“糗事百科”笑话2
import sys import requests from bs4 import BeautifulSoup # 需要爬取数据的URL url = 'https://www.qiushibaike.com/text/page/' # 循环查找第1-13页的笑话 for num in range(1,14): # 传入参数,这里模拟浏览器访问网页 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36' } # 所提取内容里面有特殊字符,需要将字符串进行translate,使用translate方法(百度了解) bmp =dict.fromkeys(range(0x10000, sys.maxunicode+1),0xfffd) # 请求网页,传入参数 r = requests.get(url + str(num), headers = headers) # translate源代码 content = r.text.translate(bmp) # 解析网页 soup = BeautifulSoup(content, 'lxml') # 提取所需信息 divs = soup.find_all(class_='article block untagged mb15 typs_hot') # 创建一个文件并将爬取到的数据保存在该文件中("a+"是追加的意思,如果没有的话就创建一个。) with open ('糗事百科笑话.txt', 'a+', encoding='utf-8') as file: # 使用循环打印出信息 for div in divs: joke = div.span.get_text() file.write(joke) print("第{}页爬取完成!".format(num))

浙公网安备 33010602011771号