首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Python爬虫设置代理

Python爬虫设置代理

作者头像
花猪
发布2022-02-22 16:16:32
发布2022-02-22 16:16:32
1.3K00
代码可运行
举报
运行总次数:0
代码可运行

前言

在写爬虫爬取github数据的时候,国内的ip不是非常稳定,在测试的时候容易down掉,因此需要设置代理。本片就如何在Python爬虫中设置代理展开介绍。

也可以爬取外网

爬虫编写

需求

做一个通用爬虫,根据github的搜索关键词进行全部内容爬取。

代码

首先开启代理,在设置中修改HTTP端口。

在爬虫中根据设置的系统代理修改proxies的端口号:

代码语言:javascript
代码运行次数:0
运行
复制
import requests
from lxml import html
import time
etree = html.etree

def githubSpider(keyword, pageNumberInit):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.62',
    }

    # 搜索的关键词
    keyword = keyword
    # 查询的起始页数
    pageNum = pageNumberInit

    # 设置一个通用的url模板
    url = 'https://github.com/search?p=%d&q={}'.format(keyword)
    # 根据代理配置端口进行修改
    proxies = {'http': 'http://127.0.0.1:1087', 'https': 'http://127.0.0.1:1087'}

    status_code = 200
    while True and pageNum:
        # 对应页码的url
        new_url = format(url % pageNum)

        # 使用通用爬虫对url对应的一整张页面进行爬取
        response = requests.get(url=new_url, proxies=proxies, headers=headers)

        status_code = response.status_code  # 状态码

        if status_code == 404:  # 最后一页
            print("===================================================")
            print("结束")
            return
        if (status_code == 429):  # 访问次数过多
            print("正在重新获取第" + str(pageNum) + "页内容....")

        if (status_code == 200):  # 正常爬取
            print("===================================================")
            print("第" + str(pageNum) + "页:" + new_url)
            print("状态码:" + str(status_code))
            print("===================================================")

            page_text = response.text
            tree = etree.HTML(page_text)
            li_list = tree.xpath('//*[@id="js-pjax-container"]/div/div[3]/div/ul/li')

            for li in li_list:
                name = li.xpath('.//a[@class="v-align-middle"]/@href')[0].split('/', 1)[1]
                link = 'https://github.com' + li.xpath('.//a[@class="v-align-middle"]/@href')[0]
                # 解决没有star的问题
                try:
                    stars = li.xpath('.//a[@class="Link--muted"]/text()')[1].replace('\n', '').replace(' ', '')
                except IndexError:
                    print("名称:" + name + "\t链接:" + link + "\tstars:" + str(0))
                else:
                    print("名称:" + name + "\t链接:" + link + "\tstars:" + stars)

            pageNum = pageNum + 1

if __name__ == '__main__':
    githubSpider("hexo",1) # 输入搜索关键词和起始页数

爬取结果如下,包含搜索结果的名称链接以及stars

后记

爬取外网的简单测试,状态码:

代码语言:javascript
代码运行次数:0
运行
复制
import requests
#配置代理
proxies={'http': 'http://127.0.0.1:1087', 'https': 'http://127.0.0.1:1087'}
response = requests.get('https://www.google.com/',proxies=proxies)
print(response.status_code)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-02-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 爬虫编写
    • 需求
    • 代码
  • 后记
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档