Python例子
- Python例子-图片验证码
- Python例子-将一个list的值加入字典,然后再插入到一个空列表
- Python例子-爬取糗事百科首页内容
- Python例子-urllib模拟游览器
- Python例子-读取远程页面并写入本地页面
- Python例子-通过装饰器实现已有函数执行时间的统计
- Python例子-使用闭包函数输出不同人的对话
- Python例子-面向对象(烤地瓜)
- Python例子-复制文件
- Python例子-计算阶乘 n! = 1 * 2 * 3 * ... * n
- Python例子-8个老师分配到3个办公室
- Python例子-求1~100中平方根是整数的数
- Python例子-求100-999之间所有的"水仙花数"
- Python例子-1、2、3、4组成互不相同不重复的三位数
- Python例子-年份是否是闰年
- Python例子-设计“过7游戏”
- Python例子-九九乘法表
- Python例子-统计字符串中,各个字符的个数
- Python例子-测试身材是否标准
- Python例子-计算1~100的累加和
- Python例子-猜拳游戏
- Python例子上公交车有座位可以坐下
Python例子-爬取糗事百科首页内容
import urllib.request import re import json def jokeCrawler(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', } req = urllib.request.Request(url,headers=headers) response = urllib.request.urlopen(req) HTML = response.read().decode('utf-8') pat =r'<div class="author clearfix">(.*?)<span class="stats-vote"><i class="number">' re_joke = re.compile(pat,re.S) # re.S匹配换行 div_list = re_joke.findall(HTML) # 返回一个列表 # print(div_list) # print(len(div_list)) dic = {} for div in div_list: # 用户名 re_u = re.compile(r'<h2>(.*?)</h2>',re.S) username = re_u.findall(div) # print(username) username = username[0].replace('\n','') # print(type(username)) # print(username) # dic[username] = username # 段子内容 re_c = re.compile(r'<div class="content">\n<span>(.*?)</span>',re.S) content = re_c.findall(div) content = content[0].replace('\n','') dic[username] = content # print(content) path = '/home/python/Desktop/pc/test/qiushi.json' with open(path,'w') as f: f.write(json.dumps(dic)) return dic url = 'https://www.qiushibaike.com/text/page/1/' info = jokeCrawler(url) print(len(info)) print(info)
最后修改:2020年3月29日 22:35