python爬虫实践2:用urllib.request爬取天气网的图片

上一个爬虫用的是打开浏览器的模式去爬取数据,执行效率是比较低下的。如果不同浏览器去爬,应该怎样获取想要的数据呢?这里需要用到urllib.request的方法,并结合正则表达式。

# -- coding: utf-8 --
from urllib import request
import re

#获取url对应的HTML源码
url = 'http://p.weather.com.cn/2017/06/2720826.shtml#p=7'
requestUrl = request.Request(url)#发送请求
responseUrl = request.urlopen(requestUrl)#打开url
html = responseUrl.read()#读取HTML源码
print(html)

#对HTML源码内容转化为string类型,并用re正则表达式匹配。r忽略转义字符。
matchUrl = r'http://[\S]*jpg'
pattern = re.compile(matchUrl)
lists= pattern.findall(repr(html))#repr() 函数将对象转化为供解释器读取的形式,返回一个对象的string格式
print(lists)
print(len(lists))



发布了46 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24601279/article/details/103663539