requests+re爬取豆瓣电影top100

这是一个非常基础的项目,可以很好地锻炼对于requests和re的使用。注释很详细,如果有大佬看到哪里有错误,还请指出,我现在还是一个小白!!!

import requests
import re
import json
import time

# 参数为url,获得该页面的html
def get_one_page(url):
    # 请求头,伪装成浏览器
    headers={
        'User-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
    }
    # 调用requests的get方法进入请求
    response=requests.get(url,headers=headers)
    if response.status_code==200:
        return response.text
    else:
        return None
# 参数为html,对HTML中我们所需数据进行提取
def parse_one_page(html):
    # 表达式分别提取rank,name,image,stars,time,score
    pattern=re.compile('
.*?board-index.*?">(.*?).*?title="(.*?)".*?' '(.*?)

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

.*?integer.*?>(.*?).*?fraction.*?>(.*?).*?
'
,re.S) # items是我们匹配的数据后返回的一个list items=re.findall(pattern,html) # 遍历list进行处理,将数据转化为一个个字典便于操作 for item in items: yield { 'rank':item[0], 'name':item[1], 'image':item[2], 'star':item[3].strip()[3:] if len(item[3])>3 else '', 'time':item[4].strip()[5:] if len(item[4])>5 else '', 'score':item[5].strip()+item[6].strip() } # 将字典格式转化为json并写入txt文件 def write_to_file(content): with open('result.txt','a',encoding='utf-8') as f: # 将字典封装为json字符串 # print(type(json.dumps(content))) # 为保证中文可以正确编码,写入文件 f.write(json.dumps(content,ensure_ascii=False)+'\n') # 将字典格式转化为json并写入json文件 # def write_to_file(content): # with open('data.json', 'w') as f: # json.dump(content, f) def main(offset): # 分析top100的页面的URL只有offset不一样 url='https://maoyan.com/board/4?offset='+str(offset) # 获取html html=get_one_page(url) # 解析HTML提取数据 for content in parse_one_page(html): # print(type(content)) write_to_file(content) # 在执行程序时候保证将所有页面进行解析 if __name__=='__main__': for i in range(10): main(offset=i*10) # 防止爬取速度过快 time.sleep(1)

你可能感兴趣的:(Python,爬虫)