爬虫基础
目录
day01
爬虫学习来源:(逆风学习网:买的 2019年3月份黑马爬虫阶段课程,很遗憾没有文档。。。)(获取方法:自行百度)
先给出爬虫的总目录:
爬虫基础知识
在自己电脑上设置爬虫的时候,需要注意几个点:
- 首先确认电脑是安装了 python2 和 python3 的吗?如果两个都安装了,而且你还想用 pip 来自动安装库,请使用 链接
- 安装的库需要看自己是否需要了,现在先安装了 repuests库,注意本文章现在只用了 python3 !!! 如果更新了库,使用的软件还是 pycharm,请更新 pycharm 的 python3 的信息,只需要在下图刷新一下就行了。
模块一:
尝试爬取网站信息:
如果结果出现乱码,注意设置编码为 UTF-8
代码:
from urllib import request
base_url = 'http://www.baidu.com'
req = request.Request(base_url)
response = request.urlopen(req)
html = response.read()
print(html)
with open('baidu.html ','wb') as f:
f.write(html)
f.close()
爬取结果:
模块二
这个是各种请求对象的使用:
代码:
import requests
if __name__ == '__main__':
url = 'http://www.baidu.com'
response = requests.get(url)
data = response.content
data_str = data.decode('utf-8')
#状态码
code = response.status_code
print(code)
print(type(code))
#请求头
requests_headers = response.request.headers
print(requests_headers)
#响应头
response_headers = response.headers
print(response_headers)
#请求 cookies——RequestsCookieJar 对象 有时是 _cookies
request_cookies = response.request._cookies
print(request_cookies)
#响应的 cookie
response_cookies = response.cookies
print(response_cookies)
#保存文件
# with open('02baidu.html','w') as f:
# f.write(data_str)
print('结束')
结果:
模块三 循环抓取页面
import requests
class TieBaSpider(object):
def __init__(self):
self.tiebaName = input('输入贴吧名字:')
self.startPage = int(input('开始页数:'))
self.endPage = int(input('结束页数:'))
self.base_url = 'http://tieba.baidu.com/f'
self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24'}
# 1.发请求
def send_request(self,tieba_params):
response = requests.get(url=self.base_url, headers=self.headers, params=tieba_params)
data = response.content
print(555)
return data
# 2.保存数据
def write_file(self, data, page):
file_pat = 'TieBa/' + str(page) + '.html'
print('正在抓取{}页...'.format(page))
with open(file_pat, 'wb') as f:
print('666')
f.write(data)
# 3.调度方法
def run(self):
for page in range(self.startPage, self.endPage + 1):
# 1.拼接参数
tieba_params = {
'kw': self.tiebaName,
'pn': (page - 1) * 50
}
# 2.发请求
data = self.send_request(tieba_params)
# 3.保存数据
self.write_file(data, page)
tool = TieBaSpider()
tool.run()
到这里就算是爬虫的基本应用了。