简单爬虫
以下是一个爬取猫眼电影top100的简单小爬虫代码,也简单记录一下我的新手学习之路。
import requests
import re
import json
import os
from requests.exceptions import RequestException
#猫眼电影网站有反爬虫措施,设置headers后可以爬取
headers = {
'Content-Type': 'text/plain; charset=UTF-8',
'Origin':'https://maoyan.com',
'Referer':'https://maoyan.com/board/4',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
#爬取网页源代码
def get_one_page(url,headers):
try:
response =requests.get(url,headers =headers)
if response.status_code == 200:
return response.text
return None
except RequestsException:
return None
#正则表达式提取信息
def parse_one_page(html):
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]
}
#猫眼TOP100所有信息写入文件
def write_to_file(content):
#encoding ='utf-8',ensure_ascii =False,使写入文件的代码显示为中文
with open('result.txt','a',encoding ='utf-8') as f:
f.write(json.dumps(content,ensure_ascii =False)+'\n')
f.close()
#下载电影封面
def save_image_file(url,path):
jd = requests.get(url)
if jd.status_code == 200:
with open(path,'wb') as f:
f.write(jd.content)
f.close()
def main(offset):
url = "https://maoyan.com/board/4?offset="+str(offset)
html = get_one_page(url,headers)
if not os.path.exists('covers1'):
os.mkdir('covers1')
for item in parse_one_page(html):
print(item)
write_to_file(item)
save_image_file(item['image'],'covers1/'+item['title']+'.jpg')
if __name__ == '__main__':
#对每一页信息进行爬取
for i in range(10):
main(i*10)
结果如下: