1.爬虫基础分为get与post请求两种方式。
get方式是最为简单
import urllib.request
>>> html = urllib.request.urlopen("http://www.fishc.com")
>>> encode_content = html.read()//获取响应的整体内容
>>> encode_content = encode_content.decode("utf-8")//进行解码
post方式则要向添加urlopen中添加第二个参数data
import urllib.parse
import urllib.request
>>> data = urllib.parse.urlencode({'word': 'hello'}).enode("utf-8")
或者是
data = bytes(urllib.parse.urlencode({'word': 'hello'}),encoding="utf-8")
#post方式为要给浏览器上传数据,因此先parse后进行encode处理使其遵循utf-8编码
>>> html = urllib.reauest.urlopen(url,data)
>>> encode_content = html.read()//读取
>>> encode_content = encode_content.decode("utf-8")//进行解码
2.有些网站可能需要添加头部信息才能进行正常的访问,从而防止爬虫式进行网页的访问,即分类当前是否为人类访问,那么处理方式为添加头部信息,声明User-Agent和Host,从而达到“欺骗”网站的目的:
方式有两种,一种是直接存储字典类型的header,另一种方式是通过addHeader方式进行添加。
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
以参数形式添加到urllib.reauest.urlopen的header参数
添加Header后的爬虫,会频繁的访问网站从而使得网站也会发现其踪迹,因此针对此加入了延迟提交数据和代理两个功能
(1)延迟提交数据
import time
time.sleep(5)
}
缺点:影响到时效性
(2)ip地址代理
该方法即是使用handler
步骤:a---- proxy_support = urllib.request.ProxyHandler(访问方式key:对应ip及端口value) #创建代理
b---- opener = urllib.request.build_opener(proxy_support) #创建包含代理的一个opener
c---- urllib.request.install_opener(opener) # 将创建的opener设置为默认方式的open
产生的opener会默认覆盖原有的open
3.scrapy
items.py :类似于实体类,通过scrapy.Filed() #定义需要爬取的字段
spider: 文件下是爬虫功能实现的具体代码
pipeline: 对爬虫后所获取到的数据进行处理,进行写入到数据库或是写入到文件等操作
settings.py:负责对整个爬虫的配置。例如请求头部headers,pipelines等
其中spider中具体代码的实现需要编写爬虫脚本,也是不同项目中爬虫的具体实现。
url---request---reponse---item---url
4.遇到的问题:
ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接
可能原因---是因为使用urlopen方法太过频繁,引起远程主机的怀疑,被网站认定为是攻击行为。导致urlopen()后,request.read()一直卡死在那里。最后抛出10054异常。
处理方式---1. 在request后面写入一个关闭的操作
2.设置sleep()等待一段时间后继续下面的操作
参考网址:https://blog.csdn.net/illegalname/article/details/77164521