ps:初学爬虫,跟着催庆才的爬虫案例实战写的!
视频网址:https://edu.hellobi.com/course/156/
1,首先导入相应的模块:
import re
import requests
from urllib3.exceptions import RequestError
import json
from multiprocessing import Pool
requests:用于处理http请求,如果没有可以用pip命令下载 pip install requests
json: 用于处理json数据格式 ,如果没有可以用pip命令下载 pip install json
requesterror:requests请求失败异常
multiprocessing:用于多线程
2,分析网页
通过检查我们可以知道这个网页请求是get请求,然后这个电影是位于网页中
通过正则提取我们需要的内容
3,获取 html网页
def get_one_page(url):
try:
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36'
}
response = requests.get(url,headers = headers)
if response.status_code == 200:
return response.text
return None
except RequestError:
return None
才能得到完整的网页源码
4,正则提取想要得到的信息
def parse_one_page(html):
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]
}
关于正则不会的可以看这个:Python正则
正则表达式提取了每部电影的 编号,图片地址,名称,主演,上映日期,评分
(.*?) 返回一个元组存到items中然后for in 遍历每部电影,yield返回一个字典的生成器,有关yield可以百度下
5,存入文件
def write_to_file(content):
with open('result.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii = False)+'\n')
f.close()
6,多线程
def main(offset):
url = "http://maoyan.com/board/4?offset="+str(offset)
html = get_one_page(url)
if html:
for item in parse_one_page(html):
write_to_file(item)
if __name__ == '__main__':
pool = Pool()
pool.map(main,[i*10 for i in range(0,10)])
完整代码:
import re
import requests
from urllib3.exceptions import RequestError
import json
from multiprocessing import Pool
def get_one_page(url):
try:
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36'
}
response = requests.get(url,headers = headers)
if response.status_code == 200:
return response.text
return None
except RequestError:
return None
def parse_one_page(html):
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')
f.close()
def main(offset):
url = "http://maoyan.com/board/4?offset="+str(offset)
html = get_one_page(url)
if html:
for item in parse_one_page(html):
write_to_file(item)
if __name__ == '__main__':
pool = Pool()
pool.map(main,[i*10 for i in range(0,10)])