【Python52--爬虫1】

一、Python如何访问互联网

采用urllib包来访问

二、理论

1、请问URL是“统一资源标识符”还是“统一资源定位符”

URI是统一资源标识符,URL是统一资源定位符。即:URI是用字符串表示某一互联网资源,URL是用字符循环表示资源的地址,因此URI是父类,URL是子类

2、urllib.request.urlopen()返回的是什么类型的数据


import urllib.request
url = "https://ilovefishc.com"
response = urllib.request.urlopen(url).read()
a = response.decode("utf-8")
print(a)

3、当目标网站使用的是自签名的证书时就会抛出错误:urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

#解决办法:导入import ssl   和 ssl._create_default_https_context = ssl._create_unverified_context

import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
url = "https://ilovefishc.com"
response = urllib.request.urlopen(url).read()
a = response.decode("utf-8")
print(a)

4、下载https://fishc.com.cn/首页,并打印前300个字节

import urllib.request
import ssl
import chardet
ssl._create_default_https_context = ssl._create_unverified_context
url = "https://fishc.com.cn/"
response = urllib.request.urlopen(url).read()
#chardet.detect(response)
print(response.decode("charmap","ignore"))

只是扩展:如果不知道网站采用的是什么编码格式,如何解决

方法:

1)、安装chardet模块:pip install

2)、导入:>>import chardet

3)、输入:>>chardet.detect(response)

  >> {'confidence': 0.99, 'encoding': 'GB2312'}

4)、如果输出的是:GB2312

5)、采用:>>

 if chardet.detect(response)['encoding'] == 'GB2312':

    response.decode('GBK')

In [1]: import urllib.request

In [2]: import ssl

In [3]: ssl._create_default_https_context = ssl._create_unverified_context

In [4]: url = "https://fishc.com.cn/"

In [5]: response = urllib.request.urlopen(url).read()

In [6]: import chardet

In [7]: chardet.detect(response)
Out[7]: 
{'encoding': 'Windows-1254',
 'confidence': 0.45397661418528873,
 'language': 'Turkish'}

#################################
#知道了编码格式是:Windows-1254',则进行后续代码编写
import urllib.request
import ssl
import chardet
ssl._create_default_https_context = ssl._create_unverified_context
url = "https://fishc.com.cn/"
response = urllib.request.urlopen(url).read()
#chardet.detect(response)
print(response.decode("charmap","ignore"))

5、写一个程序,依次访问文件中指定的站点,并将每个站点返回的内容依次存放到不同的文件中

import urllib.request
import chardet

def main():
    #初始化一个文件名的递增数字
    i = 0

    #读取url.txt文件内的每一行
    with open('url.txt',"r") as f:
        #每一行是一个URL,所以按换行符'
'分隔
        url = f.read().splitlines()

    #打开url地址
    for each_url in url:
        responsed = urllib.request.urlopen(each_url).read()

    #识别网页编码
    encode = chardet.detect(responsed)['encoding']
    if encode =='GB2312':
        encode = 'GBK'
    if encode == 'gbk':
        encode = 'charmap'

    i +=1
    filename = "url_%d.txt"%i

    with open(filename,"w",encoding=encode) as each_file:
        each_file.write(responsed.decode(encode,"ignore"))

if __name__ == '__main__':
    main()
原文地址:https://www.cnblogs.com/frankruby/p/10035737.html