python requests 正则爬虫-python爬虫教程requests
代码:
import requests
from multiprocessing import Pool
from requests.exceptions import RequestException
import re
import json
def get_one_page(url):
try:
if url==”:
return None
response=requests.get(url)
if response.status_code==200:
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
if html==”:
return None
pattern=re.compile(‘<dd>.*?board-index.*?>(d+)</i>.*?data-src=”(.*?)”.*?name”><a’
+’.*?>(.*?)</a>.*?star”>(.*?)</p>.*?releasetime”>(.*?)</p>’
+’.*?integer”>(.*?)</i>.*?fraction”>(.*?)</i>.*?</dd>’,re.S)
items=re.findall(pattern,html)
for item in items:
yield {
‘index’:item[0],
‘image’:item[1],
‘title’:item[2],
‘actor’:item[3].strip()[3:],
‘time’:item[4].strip()[5:],
‘score’:item[5]+item[6]
}
def write_to_file(content):
with open(‘result.txt’,’a’,encoding=’utf-8′) as f:#a往后追加
f.write(json.dumps(content,ensure_ascii=False)+’
’)
f.close()
def main(offset):
url=’http://maoyan.com/board/4?offset=’+str(offset)
html=get_one_page(url) # 得到html
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__==’__main__’:
# for i in range(10):
# main(i*10)
pool=Pool() #多线程
pool.map(main,[i*10 for i in range(10)])
相关文章
- Python中的网关:WSGI
- [源码解析] PyTorch 分布式 Autograd (6) ---- 引擎(下)
- JLight——JavaWeb的轻量级开发框架
- 排序算法的python实现
- python学习笔记10.1 python中的路径
- python学习笔记10.4 通过killpg杀死进程组
- Golang: 插件plugin介绍
- C/C++为什么要专门设计个do…while?
- RESTful API 设计指南
- 【Spark重点难点】你的代码跑起来谁说了算?(内存管理)
- window.onload 、$(function()function())、;(function(){}());的执行顺序(初)
- 远程代码执行 (RCE),解释:它是什么,以及如何防止它
- 2w字!最全Python办公自动化指南
- Linux crontab 命令
- shell脚本 解决“/bin/bash^M: bad interpreter: No such file or directory”
- centos 8利用crontab设置定时任务,crontab每秒运行
- [源码解读]一文读懂Vuex4源码
- Python语法必备篇——Python字符串 学习
- 开源、SaaS和API,谁将成为最后的赢家?
- 通过ansible搭建 Redis Cluster 集群环境(Docker)