终于看着python爬虫的书写了第一个爬虫程序!
首先在macOS系统安装pycharm还是非常简单的,只要去官网下载一个dmg,像正常安装程序一样拖一下就能完成啦
我是按照《Python3 网络爬虫开发实战》书上的例子写的,主要是把代码搬运过来写个注视便于自己理解吧。
这是一个爬取猫眼前100电影排行榜的程序,主要代码如下:
#json是一种轻量级的数据交换格式,便于人阅读和编写JSON常用做网站异步请求的数据交换,网站异步请求,对服务器进行请求后,服务端进行处理后,将处理后的结果通过JSON格式传回给客户,客户端经过解析,表现出来。
import json
import requests
from requests.exceptions import RequestException
#正则表达式
import re
import time
import io
#获取一个页面
def get_one_page(url):
try:
#请求头,添加请求头最常用的用法是通过修改User-Agent来伪装浏览器
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'
}
#get请求
response = requests.get(url, headers=headers)
#print(response.url)
#状态码为200代表请求成功
if response.status_code == 200:
#print response.text
return response.text
return None
except RequestException:
return None
def parse_one_page(html):
#re.complie()可以将正则字符串编译成正则表达式对象,以便在后面的匹配中复用
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]
}
#通过json.dumps方法实现字典的序列化,并指定ensure_ascii=False,保证输出结果是中文形式而不是Unicode编码
def write_to_file(content):
with io.open('/Users/wlj/Desktop/result.txt', 'a', encoding='utf-8') as f:
#print(json.dumps(content, ensure_ascii=False) + '\n')
f.write(json.dumps(content, ensure_ascii=False) + '\n')
#用main()方法来调用前面实现的方法,接受一个offset值作为偏移量,构造哦url进行爬取
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)
代码运行结果:
这样运行出来了还是比较顺利的。
中间的几个小插曲:
1.关于mac电脑的文件路径,可以打开终端,把想查看路径的文件拖进去,即可显示完整路径然后复制即可。
2.打开文件open的“a”代表如果文件不存在就自己创建一个,开始的时候是用了一个以前现有的文件,结果可能是文件编码格式不太对,一直输出乱码,把那个文件删了跑程序的时候自己创建就好了。
3.python3的open()函数里没有encoding这一项,所以import io 用io.open()打开文件,规定encoding格式。
4.猫眼的网页有一个登录滑块验证,运行的时候第一次会失败,可以手动打开猫眼的那个网页验证一下,然后再次运行就可以了。