抓取首页
首先我们定义一个get_one_page方法,来获取首页(http://maoyan.com/board/4 )的源代码。获取源代码之后,解析页面,提取出我们所需要的信息。
大致思路:构造headers头,判断目标网站的响应状态码是否是200,然后通过requests库的get方法抓取源代码。
正则提取
注意点:Elements选项中的源码可能经过JS操作而与原始请求不同,需要从Network中查看。
可以看到一部电影信息对应源代码的一个dd节点
正则提取的具体实现
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)
方法:
re.compile():将正则字符串编译成正则表达式对象,以便在后面的匹配中重复使用。
re.finall():该方法会搜索整个字符串,然后返回匹配正则表达式的所有内容。
修饰符:
re.S:使.匹配包括换行在内的所有字符。
处理匹配结果
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]
}
这里的yield是一个关键字,大致解释如下:
如果一个函数包含 yield 表达式,那么它是一个生成器函数;调用它会返回一个特殊的迭代器,称为生成器。
因为介绍yield这个关键字需要一个单独的篇幅,具体解析请移步我的另一篇文章:https://www.minghaohao.cn/index.php/archives/46/
写入文件
with open('result.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
dumps():实现字典的序列化。
分页爬取
给我们的链接传入offset参数,这里要能够发现随着我们向后翻页,豆瓣榜单的url也在变化:
http://maoyan.com/4?offset=10 → http://maoyan.com/4?offset=20
for i in range(10):
main(offset=i * 10)
源代码
整合思路,源代码如下:
import json
import requests
from requests.exceptions import RequestException
import re
import time
def get_one_page(url):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/65.0.3325.162 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
except RequestException:
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]
}
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 main(offset):
url = 'http://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
for item in parse_one_page(html):
print(item)
write_to_file(item)
if __name__ == '__main__':
for i in range(10):
main(offset=i * 10)
time.sleep(1)