Python3 之 爬取网站页面
来源:互联网 发布:sql语句基础教程 编辑:程序博客网 时间:2024/06/05 17:53
Python3 抓取网页需要用到urllib.request模块
import urllib.requestdef download(url, free_proxy=None, user_agent='test', num_retries=2, data=None): print("download开始", url) # 设置headers 中的用户代理,默认值是test headers = {"User_agent": user_agent} # 将用户代理添加到请求中 request = urllib.request.Request(url, data, headers=headers) # 创建句柄 opener = urllib.request.build_opener() # 判断如果proxy是否有值 if free_proxy: # 获取ip代理协议和IP代理 proxy_params = {urllib.request.urlparse(url).scheme: free_proxy} # 将IP代理设置添加到句柄中 opener.add_handler(urllib.request.ProxyHandler(proxy_params)) try: # 使用句柄的open()打开网页,read()读取内容 html5 = opener.open(request).read() # 异常处理,捕获异常 except urllib.request.URLError as e: # 打印异常原因 print("download error", e.reason) html5 = None # 判断重新加载次数是否大于0 if num_retries > 0: # 判断 页面code是否在500和600之间 if hasattr(e, 'code') and 500 <= e.code < 600: # 调用自身 html5 = download5(url, free_proxy, user_agent, num_retries - 1) # 如果没有decode('utf-8'),数据会是b''格式 return html5.decode('utf-8')# 示例网址url = 'http://www.thefaceshop.com.cn/store-locations'# 打印抓下来的网页print(download(url))
运行结果:
阅读全文
1 0
- Python3 之 爬取网站页面
- python3 爬取网站图片
- Python3.6爬取网站图片
- python3爬取html页面内容
- python3 [入门基础实战] 爬虫入门之爬取豆瓣读书随笔页面
- python3爬取新闻网站的所有新闻-新手起步
- python3.5 爬取bing搜索结果页面标题、链接
- python3爬虫(1)--百度百科的页面爬取
- python3爬虫(2)--爬取糗事百科页面
- Python3.X 爬虫实战(动态页面爬取解析)
- [实战演练]python3使用requests模块爬取页面内容
- [实战演练]python3使用requests模块爬取页面内容
- Python3爬取图片
- python3爬虫 爬取图片,爬取新闻网站文章并保存到数据库
- Python3爬虫入门之爬取豆瓣Top250电影名称
- Python3之爬虫爬取豆瓣读书Top250
- [python3]爬虫实战一之爬取糗事百科段子
- python scrapy之爬取 zhengfu网站
- Openresty nginx 服务的启动 停止 重启命令
- poj 1741 Tree(树分治)
- js获取当前日期时间/年份/月份
- UVA
- java.util.zip.ZipException: duplicate entry(重复依赖多版本的类库)
- Python3 之 爬取网站页面
- spring-boot启动报错【This application has no explicit mapping for /error.....】
- Git 在团队中的最佳实践--如何正确使用Git Flow
- cs和bs比较
- 实现table框内的数字和字母自动换行
- 阿里2017算法工程师在线笔试编程——8月25日
- 内核库函数
- VMware-ubuntu 和windows共享文件夹
- MYSQL死锁