版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mx_windxiao/article/details/52854326
爬虫,全称网络爬虫,是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。
要写爬虫,首先需要写的程序能连接到网络,Python提供了urllib模块可以用来连接网络,一个简单的例子如下:
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read())
运行结果如下图所示:
一堆代码,表示已经把百度首页的代码打开了,看代码前面,编码应该是UTF-8的,把这些代码转换成UTF-8的再来看看:
代码:
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
html = response.read()
html = html.decode('utf-8')
print(html)
虽然也很乱,好歹比刚才好点了。。。。。。。。
每次要看编码格式很麻烦,Python里有个三方的模块叫做chardet,是用来识别编码类型的,非常的好用,安装三方模块呢,推荐使用pip方法,打开windows的命令提示符
输入pip install chardet 即可,如下图所示:
安装成功后就可以调用了,用法如下:
import urllib.request
import chardet
response = urllib.request.urlopen("http://www.bilibili.com").read()
a = chardet.detect(response)
print(a)
---------------------------------------------------------------------
{'confidence': 0.99, 'encoding': 'utf-8'}
如上所示,返回了编码是utf-8,可能性是0.99,下面再写一个用户输入url然后返回该地址的编码的例子:
import urllib.request
import chardet
def main():
url = input('请输入网址:')
response = urllib.request.urlopen(url)
html = response.read()
encode = chardet.detect(html)['encoding']
if encode == 'GB2312':
encode = 'GBK'
print('此网页编码为:%s' % encode)
main()
--------------------------------------------------------
请输入网址:http://www.baidu.com
此网页编码为:utf-8
请输入网址:http://www.bilibili.com
此网页编码为:utf-8