Python3爬虫程序 进阶:伪装浏览器、超时功能、保存数据

import urllib.request
import http.cookiejar
 
# head: dict of header
def makeMyOpener(head = {
    'Connection': 'Keep-Alive',
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
}):
    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    header = []
    for key, value in head.items():
        elem = (key, value)
        header.append(elem)
    opener.addheaders = header
    return opener
 
def saveFile(data):
    save_path = 'D:\\output.out'
    f_obj = open(save_path,'wb')
    f_obj.write(data)
    f_obj.close()
 
oper = makeMyOpener()
uop = oper.open('http://sjzlq.hbzwfw.gov.cn/art/2018/4/17/art_699_957463.html', timeout = 1000)
data1 = uop.read()    #.decode('utf-8')
saveFile(data1)
print(data1)

原文链接:https://blog.youkuaiyun.com/drdairen/article/details/51089136

类似博文:python-快速使用urllib爬取网页 https://blog.youkuaiyun.com/qq_38262266/article/details/78882479

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值