Python爬虫爬取网页数据并存储(一)
- 环境搭建
- 爬虫基本原理
- urllib库使用
- requests库使用
- 正则表达式
- 一个示例
环境搭建
1.需要事先安装anaconda(或Python3.7)和pycharm
*anaconda可在中科大镜像下下载较快
2.安装中遇到的问题:
*anaconda(记得安装过程中点添加路径到path里,没添加的话手动添加:
计算机右键属性——高级系统设置——环境变量——用户/系统变量path路径中,添加 C:\Users\Aurora\Anaconda3;(anaconda安装路径))
打开jupyter notebook ,出现页面空白解决方案:
打开 C:\Users\自己的用户名.jupyter\jupyter_notebook_config.py
在末尾输入以下代码:
import webbrowser
webbrowser.register(“Chrome”, None, webbrowser.GenericBrowser(u"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"))
c.NotebookApp.browser = u’Chrome’
##浏览器名,浏览器路径(通过右键属性可以看到路径)
*anaconda ,打开cmd/anaconda prompt,输入conda list 即可查看已有的包,还需添加可用 conda install package_name 来添加在本次网络爬虫过程中,我们需要的库有: re,urllib(这两个库为Python内置库,不需要添加),requests,lxml(anaconda中已存在,Python3.7安装装需要使用pip,下载whl软件),beautifulsoup4,json*pycharm基础设置问题:设置为conda环境下Python3.7
爬虫基本原理
什么是爬虫?
爬虫是请求网站并提取数据的自动化程序
从简单的例子开始:
我们随便打开一个网站,我们在百度上搜索新闻,右键,审查元素
会得到这样一个响应,点Name那一栏唯一的一个news.baidu.com,我们会发现以下信息:
我们就通过这些html代码来获取信息。
让计算机代替人工来提取信息就是我们要用Python所要实现的任务。
所以我们就可以通过以上过程总结爬虫的基本原理
1.发出请求:即发出一个Request
2.获取响应内容:如果服务器正常响应就可以得到一个Response
3.解析内容:得到的内容是HTML,可以用正则表达式,网页解析库进行解析。
4.保存数据
urllib库使用
urllib.request 请求模块
//简单使用
import urllib.request
request = urllib.request.Request('http://www.baidu.com')
response = urllib.request.urlopen(request)
print(response.read(),decode('utf-8'))
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块
(建议用下面的requests库而不使用urllib库)
requests库使用
解析json
//
import json
import requests
response = request.get("http://httpbin.org/get")
print(response.json())
//添加headers参数(应对一些反爬虫的最简单的方法)
//以猫眼电影top100为例import requestsurl = 'https://maoyan.com/board/4?offset=0'headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}response = requests.get(url,headers = headers)response.encoding = 'utf-8'
正则表达式
一个示例
import requests
from requests.exceptions import RequestException
import re
import jsondef get_one_page(url,headers):try:response = requests.get(url,headers = headers)response.encoding = 'utf-8'if response.status_code == 200:return response.textreturn Noneexcept RequestException:return Nonedef 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]}
//写入result.txt文件中
def write_to_file(content):with open('result.txt', 'a') as f:f.write(json.dumps(content) + '\n')f.close()def main():
//猫眼电影爬取需添加headers,从用户角度访问url = 'https://maoyan.com/board/4?offset=0'user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent': user_agent}html = get_one_page(url, headers)for item in parse_one_page(html):print(item)write_to_file(item)if __name__ == '__main__':main()
运行结果:
上述例子为抓取一页信息并存储,若要抓取多页的信息,需要引入Pool模块,用多线程并发抓取,如下构造:
def main(offset):url = 'https://maoyan.com/board/4?offset=0'user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent': user_agent}html = get_one_page(url, headers)for item in parse_one_page(html):print(item)write_to_file(item)
if __name__ == '__main__':p = Pool()p.map(main.[i*10 for i in range(10)]