您当前的位置: 首页 >  网络

TechGuide

暂无认证

  • 6浏览

    0关注

    176博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python3网络爬虫系列(三)爬取给定URL网页(访问量、阅读量)实例

TechGuide 发布时间:2020-04-12 19:15:12 ,浏览量:6

点赞再看,养成习惯,您动动手指对原创作者意义非凡🤝 备战2021秋招面试 微信搜索公众号【TechGuide】关注更多新鲜好文和互联网大厂的笔经面经。 作者@TechGuide

前言

已经搭建好代理IP池之后,就可以尝试用获得的代理IP访问给定URL,爬取页面,具体的源码和更多说明在github库Simulate-clicks-on-given-URL里,供大家学习。

代码 这段代码可以返回我们需要的用户IP
PROXY_POOL_URL = 'http://localhost:5555/random'

def get_proxy():
    try:
        response = requests.get(PROXY_POOL_URL)
        if response.status_code == 200:
            ip = response.text
            #设置代理,格式如下
            proxy_ip = "http://" + ip
            proxy_ips = "https://" + ip
            proxy = {"https":proxy_ips,"http":proxy_ip} 
            return proxy
    except ConnectionError:
        return None
共享cookie,保持登陆状态
def get_cookie(url,urls):
    if(url==urls[0]):
        f=open(r'cookie0.txt','r')#打开所保存的cookies内容文件
    if(url==urls[1]):
        f=open(r'cookie1.txt','r')#打开所保存的cookies内容文件
    if(url==urls[2]):
        f=open(r'cookie2.txt','r')#打开所保存的cookies内容文件
    cookies={}#初始化cookies字典变量
    for line in f.read().split(';'):   #按照字符:进行划分读取
        #其设置为1就会把字符串拆分成2份
        name,value=line.strip().split('=',1)
        cookies[name]=value  #为字典cookies添加内容
    return cookies
爬取网页
def simulate_click(urls,num):
        success = 0
        fail = 0        
        referer_list=[
                'https://www.google.com/search?q=csdn&rlz=1C1EJFC_enSE810SE810&oq=csdn&aqs=chrome..69i57j69i59l2j0l5.2484j0j8&sourceid=chrome&ie=UTF-8',
                'http://blog.csdn.net/',
                'https://blog.csdn.net/weixin_41896265',
                'https://www.sogou.com/tx?query=%E4%BD%BF%E7%94%A8%E7%88%AC%E8%99%AB%E5%88%B7csdn%E8%AE%BF%E9%97%AE%E9%87%8F&hdq=sogou-site-706608cfdbcc1886-0001&ekv=2&ie=utf8&cid=qb7.zhuye&',
                'https://www.baidu.com/s?wd=csdn&rsv_spt=1&rsv_iqid=0xa615ef5b0000b256&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=78040160_26_pg&ch=8&rsv_enter=1&rsv_dl=tb&rsv_sug2=0&inputT=1113&rsv_sug4=1528'
            ]
         
        while(num>0):
            #随机user_agent和Referer
            ua = UserAgent()
            headers = {
                'user-agent': ua.random,  #随机agent
                'Referer': random.choice(referer_list),  #表示不是凭空产生
            }
            proxies = get_proxy()
            for url in urls:
                cookies = get_cookie(url,urls)
                print("【正在访问】{}".format(url))
                try:
                    session = requests.session()
                    resp=session.get(url,headers=headers,proxies=proxies,cookies=cookies,timeout=3) 
                    if resp.status_code == requests.codes.ok:
                        print("---------------------------\n")
                        print(resp.text[10000:30000])
                        print("---------------------------\n")
                        success+=1
                        print("【访问成功{}】".format(success)+proxies["https"])
                        time.sleep(40)
                except Exception as e:
                #无响应则print出该代理ip
                    fail+=1
                    print ('【访问失败{}/】'.format(fail)+proxies["https"])
                    print("访问异常--->"+str(e)+"\n")
                    proxies = get_proxy()
                    time.sleep(0.5)
            num-=1
        print("-----------共访问{0}次,成功{1}次,失败{2}次--------------".format(success+fail,success,fail))

if __name__ == '__main__':
    num=100   # 运行次数,酌情修改
    urls=['你的url0','你的url1','你的url2']
    simulate_click(urls,num)
本代码仅供学习网络爬虫相关使用,大家玩的开心! 您的鼓励是我创作的源泉,如果你有收获,点个赞吧👍

除此以外,我还陆续更新了其他网络爬虫相关的学习笔记。如果看到这里的话,说明你有认真看这篇文章,希望你能有所收获!最后,欢迎交流指正! python3网络爬虫系列(一)Redis库安装原来只需这样简单三步 python3网络爬虫系列(二)用这一招!我终于有了免费好用的代理IP池 python3网络爬虫系列(三)爬取给定URL网页(访问量、阅读量)实例

关注
打赏
1665329535
查看更多评论
立即登录/注册

微信扫码登录

0.0437s