Python3.6
库:urllib3, bs4
主程序是抓取亚马逊图书销售排名数据,但是亚马逊应该是加了反爬虫,拒绝疑似机器人的请求,这部分暂时以百度代替。
其实简单的页面抓取,常用的urllib.request就能实现,但是urllib3功能更多,应用前景更广,需要学习。
首先导入模块:
import urllib3, bs4
定义要访问的页面:
urltest = 'https://www.baidu.com'
定义函数,这里对比两种解码方法:
def httpget(): http = urllib3.PoolManager() #首先产生一个PoolManager实例 urllib3.disable_warnings() #忽略https的无效证书警报 page = http.request('GET','%s'%urltest) #发起GET请求 print(page.status) #服务器返回的代码 print(page.data) #服务器返回的数据,返回的是xml字符串 print(page.data.decode()) #利用默认'utf-8'编码格式去解码 res = bs4.BeautifulSoup(page.data,'lxml') #利用lxml模块解码 print(res) return None
执行函数httpget()输出结果:
200 b'<!DOCTYPE html><!--STATUS OK--><body link="#0000cc"><div ...(#省略)
<!DOCTYPE html><!--STATUS OK--> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <link rel="dns-prefetch" href="//s1.bdstatic.com"/> <link rel="dns-prefetch" href="//t1.baidu.com"/> <link rel="dns-prefetch" href="//t2.baidu.com"/> <link rel="dns-prefetch" href="//t3.baidu.com"/> <link rel="dns-prefetch" href="//t10.baidu.com"/> <link rel="dns-prefetch" href="//t11.baidu.com"/> <link rel="dns-prefetch" href="//t12.baidu.com"/> <link rel="dns-prefetch" href="//b1.bdstatic.com"/> <title>百度一下,你就知道</title> ...(#省略)
...(#省略)
</body></html> <!DOCTYPE html> <!--STATUS OK--><html> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type"/> <meta content="IE=Edge" http-equiv="X-UA-Compatible"/> <link href="//s1.bdstatic.com" rel="dns-prefetch"/> <link href="//t1.baidu.com" rel="dns-prefetch"/> <link href="//t2.baidu.com" rel="dns-prefetch"/> <link href="//t3.baidu.com" rel="dns-prefetch"/> <link href="//t10.baidu.com" rel="dns-prefetch"/> <link href="//t11.baidu.com" rel="dns-prefetch"/> <link href="//t12.baidu.com" rel="dns-prefetch"/> <link href="//b1.bdstatic.com" rel="dns-prefetch"/> <title>百度一下,你就知道</title> ...(#省略)
...(#省略)
</body></html> Process finished with exit code 0
在这里两种解码方式都没出错,但是如果换成比较复杂的页面,普通的decode()方式就容易报错。
比如京东这个页面:
url = 'https://item.jd.com/6072622.html'
将urltest替换成url之后执行代码,执行结果如下:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 146: invalid start byte