爬虫小探-Python3 urllib.request获取页面数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了爬虫小探-Python3 urllib.request获取页面数据相关的知识,希望对你有一定的参考价值。

使用Python3 urllib.request中的Requests()和urlopen()方法获取页面源码,并用re正则进行正则匹配查找需要的数据。

#forex.py
#
coding:utf-8 ‘‘‘ urllib.request.urlopen() function in Python 3 is equivalent to urllib2.urlopen() in Python2 urllib.request.Request() function in Python 3 is equivalent to urllib2.Request() in Python2 ‘‘‘ #python3.5 import urllib.request #python2.7 #import urllib #import urllib2 import re def Gethtml(url, referer): user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:53.0) Gecko/20100101 Firefox/53.0" headers={"User-agent":user_agent,referer:referer} #python3.5 req=urllib.request.Request(url,headers=headers) response=urllib.request.urlopen(req,timeout=10) #python2.7 #req=urllib2.Request(url,headers=headers) #response=urllib2.urlopen(req,timeout=10) return response.read() url=referer="http://quote.forex.hexun.com/EURUSD.shtml" html = str(Gethtml(url, referer)) reg = r([0-1]{1}\.[0-9]{4}) i = re.compile(reg) r = re.findall(i, html) print("Hexun ERUUSD:\nCur | Open | Yesterday | Low | High") print(r)

运行:python forex.py

输出:

Hexun ERUUSD:
Cur   |     Open |  Yesterday  |  Low  |  High
[‘1.1278‘, ‘1.1211‘, ‘1.1211‘, ‘1.1203‘, ‘1.1285‘]

referer是反盗链,服务器会识别headers中的referer是不是它自己,如果不是,有的服务器不会响应,timeout=10 是超时设定。
参考:

以上是关于爬虫小探-Python3 urllib.request获取页面数据的主要内容,如果未能解决你的问题,请参考以下文章

用python抓取的网页保存后为啥乱码?

python urllib学习

第一篇 - bsp抓取python中文开发者社区中的所有高级教程

REG小探

Fiddler小探(中)

Fiddler小探(小结篇)