squrrel mysql json_Python爬虫正则案例:爬取猫眼电影

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

67ad77a02e7005ae18ad5c56153b41b3.png

以下文章来源于云+社区,作者 听城

转载地址

https://blog.csdn.net/fei347795790?t=1

7d22172bc77625e69d0850b99db5f387.gif

主要内容

requests设置headers,防止反爬

爬取内容

结果json保存

多线程抓取

设置headers

设置headers的主要目的就是防止用户请求被请求页面判定为恶意请求,最基本的就是要让用户的请求模拟浏览器请求的方式。通常在headers设置user-agent来起到模拟浏览器的方式。

session = requests.Session()

headers = {

'Connection': 'keep-alive',

'Accept': 'text/html, */*; q=0.01',

'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',

'Accept-Encoding': 'gzip, deflate, sdch',

'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'

}

爬取内容

我们使用正则表达式方式来获取我们想要的数据。这里会用re.compile()函数,该函数根据包含的正则表达式的字符串创建模式对象。可以实现更有效率的匹配。在直接使用字符串表示的正则表达式进行search,match和findall操作时,python会将字符串转换为正则表达式对象。而使用compile完成一次转换之后,在每次使用模式的时候就不用重复转换。当然,使用re.compile()函数进行转换后,re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式。

pattern = re.compile('

.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name">'

+ '(.*?).*?"star">(.*?)

.*?releasetime">(.*?)'

+ '.*?integer">(.*?).*?fraction">(.*?).*?

', re.S)

# 匹配所有符合条件的内容

items = re.findall(pattern, html)

结果json保存

# ensure_ascii=False是为了中文正常显示

with open('result.txt', 'a', encoding='utf-8') as f:

f.write(json.dumps(content, ensure_ascii=False) + '\n')

多线程抓取

from multiprocessing import Pool

pool = Pool()

pool.map(main,[i*10 for i in range(10)])

全部代码

import re

import os

import json

import requests

from multiprocessing import Pool

from requests.exceptions import RequestException

session = requests.Session()

headers = {

'Connection': 'keep-alive',

'Accept': 'text/html, */*; q=0.01',

'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',

'Accept-Encoding': 'gzip, deflate, sdch',

'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'

}

def get_one_page(url):

try:

response = session.get(url,headers=headers)

if response.status_code == 200:

return response.text

return None

except RequestException:

return 'RequestException'

def parse_one_page(html):

print('parse page')

#re.S是为了匹配换行符

pattern = re.compile('

.*?board-index.*?>(\d+).*?data-src="(.*?)".*?name">'

+ '(.*?).*?"star">(.*?)

.*?releasetime">(.*?)'

+ '.*?integer">(.*?).*?fraction">(.*?).*?

', 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:

f.write(json.dumps(content, ensure_ascii=False) + '\n')

def save_image_file(url, path):

'''

保存电影封面

'''

ir = requests.get(url)

if ir.status_code == 200:

with open(path, 'wb') as f:

f.write(ir.content)

f.close()

def main(offset):

url = 'http://maoyan.com/board/4?offset=' + str(offset)

html = get_one_page(url)

# 封面文件夹不存在则创建

if not os.path.exists('covers'):

os.mkdir('covers')

for item in parse_one_page(html):

#print(item)

write_to_file(item)

save_image_file(item['image'], 'covers/' + '%03d' % int(item['index']) + item['title'] + '.jpg')

if __name__ == '__main__':

# for i in range(10):

# main(i+10)

pool = Pool()

pool.map(main,[i*10 for i in range(10)])

本文分享 CSDN - 松鼠爱吃饼干。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值