19.1 Python入门之爬虫

网络爬虫


网络爬虫又称网页蜘蛛,即在互联网上捕获我们需要的资源


搜索引擎即靠大量的爬虫对网页的每个关键词进行索引,建立索引数据库,再经过复杂的算法排序,将得到的结果与关键词的相关度高低,依次排列


Python访问互联网


urllib包,URL为网页的地址,lib为库(library)的缩写


URL的一般格式为:protocol://hostname[port]/path/[;parameters][?query]#fragment

[]为可选项


对照上述的一般格式,可见URL由三部分组成

1)协议,常见的有http,https,ftp,file(访问本地文件夹),ed2k(电驴的专用链接)


2)存放资源的服务器的域名系统(DNS)主机名或IP地址(包含端口号,各种传输协议有默认的端口号,如http的默认端口号为80)


3)主机资源的具体地址,如目录和文件名


第一部分和第二部分不可缺少,第三部分有时可省略


urllib包总共有四个模块,第一个模块包含对服务器请求的发出,跳转,代理和安全等方面


通过urllib.request.urlopen()函数访问网页


>>>import urllib.request

>>>response = urllib.request.urlopen("www.baidu.com")

>>>html = response.read()

>>>print(html)

b'<......


可见同在浏览器上使用审查元素功能(浏览器自带的调试插件)看到的内容不一样

因为Python爬取的是内容以utf-8编码的bytes对象(打印的字符串前边有个b,表示bytes对象,理解为字符串的每一个字符存放一个字节的二进制数据),还原为带中文的HTML代码,则对其进行解码,将其变成Unicode编码


>>>html = html.decode("utf-8")

>>>print(html)


编码


编码即约定的协议,如ASCII码,该编码设计时只采用一个字节储存,后来发现一个字节远远不够,Unicode编码应运而生,该编码针对不同文本采用不同实现方式,如UTF-8编码是可变长的编码,当文本是ASCII编码的字符时,用一个字节存放,其余字符,采用1-3个字节存放(根据算法)


实例


用Python实现下载猫图片操作


>>>import urllib.request


response = urllib.request.urlopen("http://placekitten.com/g/200/300")

cat_img = response.read()

with open('cat.jpg','wb') as f:

   f.write(cat_img)


分析:urlopen的url参数可以是一个字符串也可以是Request对象(见下),若传入一个字符串,则Python默认先将目标字符串转换为Request对象,再传给urlopen函数(见上)


req = urllib.request.Request("http://placekitten.com/g/200/300")

response = urllib.request.urlopen(req)


分析:urlopen返回一个类文件对象,所以可用read()方法来读取内容


其他函数


geturl() :返回请求的url

info():返回一个httplib.HTTPMessage对象,包含远程服务器返回的头信息

getcode():返回HTTP状态码


翻译文本


在客户端和服务器间进行请求-响应,两种最常用的方法是GET和POST,GET指从服务器请求数据(有时也会用于提交数据),POST则是向指定的服务器提交要被处理的数据


HTTP是基于请求-响应的模式


客户端发出请求:Request

服务器作出响应:Response


Request Headers是客户端发送请求的Headers,被服务器判断是否是非人类(代码)的访问,通过User-Agent来识别,若采用Python访问,该值为Python-urlliv/3.4,但其实这个可以自定义


urlopen()函数有一个data参数,若给该参数赋值,则HTTP的请求是使用POST请求,若该值为NULL,则HTTP的请求是使用GET方式,且data参数的值必须符合规定格式,要用

urllib.parse.urlencode()将字符串转换为该格式


import urllib.request

import urllib.parse


url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult = rule&smartresult= ugc&sessionFrom = http://www.youdao.com/"

data = {}

data['type'] = 'AUTO'

data['i'] = 'I love you'

data['doctype'] = 'json'

data['xmlVersion'] = '1.6'

data['keyfrom'] = 'fanyi.web'

data['ue'] = 'UTF-8'

data['typoResult'] = 'true'

data =urllib.parse.urlencode(data).encode('utf-8')

response = urllib.request.urlopen(url,data)

html = response.read().decode('utf-8')

print(html)


结果是JSON格式的字符串(JSON是轻量级的数据交换格式,即用字符串将Python的数据机构封装起来),需要解析该JSON格式的字符串


>>>import json

>>>json.loads(html)


结果为字典形式


最终代码

import urllib.request

import urllib.parse

import jason


content = input('what to translate:')

url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult = rule&smartresult= ugc&sessionFrom = http://www.youdao.com/"

data = {}

data['type'] = 'AUTO'

data['i'] = 'I love you'

data['doctype'] = 'json'

data['xmlVersion'] = '1.6'

data['keyfrom'] = 'fanyi.web'

data['ue'] = 'UTF-8'

data['typoResult'] = 'true'

data =urllib.parse.urlencode(data).encode('utf-8')

response = urllib.request.urlopen(url,data)

html = response.read().decode('utf-8')

target = json.loads(html)

print("翻译结果: %s" %(target['translateResult'][0][0]['tgt']))

#字典索引层数略多


隐藏


有的网站会检查链接的来源,所以要隐藏,显得像人类访问


修改User-Agent


Request有个headers参数,设置该参数伪造成浏览器访问,设置该参数有两种途径,其一实例化Request对象时将header参数传进去或通过add_header()方法向Request对象添加headers


法1:要求headers必须是字典形式

修改内容


head = {}

head['Referer'] = 'http://fanyi.youdao.com'

head[User - Agent'] = ......#too much content


req = urllib.request.Request(url,data,head)

response = urllib.request.urlopen(req)


法二:在Request对象生成之前通过add_header()方法添加进去


修改内容

req.add_header('Referer','http://fanyi.youdao.com')

req.add_header('User-Agent','.......')#too much content

response = urllib.request.urlopen(req)


但通过修改User-Agent实现隐藏时,若服务器通过检测访问频率,当达到某阈值,填写验证码,则会露馅,解决这一问题,有两种方法,其一延迟提交时间,其二使用代理


延迟提交数据


通过time模块实现


import urllib.request

import urllib.parse

import jason

import time



url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult = rule&smartresult= ugc&sessionFrom = http://www.youdao.com/"

while True:

  content = input('what to translate:')

  if content == 'q!':

      break  #q! symbolizes exit

  data = {}

  data['type'] = 'AUTO'

  data['i'] = 'I love you'

  data['doctype'] = 'json'

  data['xmlVersion'] = '1.6'

  data['keyfrom'] = 'fanyi.web'

  data['ue'] = 'UTF-8'

  data['typoResult'] = 'true'

  data =urllib.parse.urlencode(data).encode('utf-8')

  req.add_header('Referer','http://fanyi.youdao.com')

  req.add_header('User-Agent','.......')#too much content

  response = urllib.request.urlopen(req)

  html = response.read().decode('utf-8')

  target = json.loads(html)

  print("翻译结果: %s" %(target['translateResult'][0][0]['tgt']))

  time.sleep(5)


该方法会降低程序的工作效率


使用代理


代理即代替你访问,然后把访问到的内容转发给你


使用代理步骤


(1)proxy_support = urllib.request.ProxyHandler({})

    #参数是一个字典,字典的键是代理类型,如http,ftp或https,字典的值是代理的IP地址和对应的端口号


 (2)opener = urllib.request.build_opener(proxy_support)

  #opener看作是私人定制,当使用urlopen()函数打开网页,则用户在使用默认的opener在工作,而opener可定制,如给其定制特殊的headers或特定的代理IP

  #此处使用build_opener创建一个私人订制的opener


 (3)urllib.request.install_opener(opener)

  #将定制好的opener安装到系统,此后只要使用普通的urlopen()函数,则以定制好的opener工作,若不想替换默认的opener,则不安装到系统中,通过opener.open()方法使用定制的opener打开网页


范例

import urllib.request


url = 'http://www.whatismyip.com.tw/'

proxy_support = urllib.request.ProxyHandler({'http':'211.138.121.38:80'})

#211.138.121.38:80为代理IP

opener = urllib.request.build_opener(proxy_support)

urllib.request.install_opener(opener)

response = urllib.request.urlopen(url)

html = response.read().decode('utf - 8')

print(html)


字符串在Python里是Unicode编码,所以编码转换时,先将返回的bytes对象的数据解码(decode)为Unicode,在转换为其他编码







猜你喜欢

转载自blog.csdn.net/lwz45698752/article/details/79243583
今日推荐