Python爬虫:获取Github用户主页链接并分析

Python爬虫:获取Github用户主页链接并分析

  • 引入
  • 一、初始化
  • 二、根据用户链接获取用户信息
  • 三、结果写入Excel表中并导出
  • 总结


引入

相信有朋友遇到需要批量爬取Github用户粉丝和关注用户的主页链接,然后进入对应主页链接进行用户信息分析的工作。我用Python实现了爬取用户的关注和粉丝用户,这里做一个分享。
以下我分为几个部分对Python代码进行逐段分析。


一、初始化

def __init__(self):
    self.headers = {
        'Referer': 'https://github.com/',  //填入具体的访问地址
        'User-Agent': str(UserAgent().random), #采用随机User-Agent
        //需要引入包  代码:from fake_useragent import UserAgent
        'Host': 'github.com'
    }
    self.target_username = 'paulirish'  #爬取用户的用户名
    self.session = requests.Session()

二、根据用户链接获取用户信息

page = 0
page += 1
//定义需要访问的链接结构
 followers_url = f'https://github.com/{self.target_username}?page={page}&tab=followers'  
  try:
      response = requests.get(followers_url, headers=headers, timeout=100, verify=False)
      html = response.text
      //扫描到最后一页即退出
      if 've reached the end' in html:
          break
       //利用BeautifulSoup对网页进行解析
      soup = BeautifulSoup(html, 'lxml')
      //找寻需要的标签
      for name in soup.find_all('span', class_='Link--secondary pl-1'):
      		//确保需要分析的主页链接是有效的并且不重复的
          if len(name.text) > 0 and name.text not in toCheckUrl:
              toCheckUrl.append(name.text)
  except:
      pass
   //设置自动休眠,降低Github判断为爬虫程序的可能性
  time.sleep(random.random() + random.randrange(0, 2))
  //更新下一个需要访问的链接
  headers.update({'Referer': followers_url})

有兴趣的同学可以去了解一下BeautifulSoup的知识
BeautifulSoup学习链接: Python中BeautifulSoup库的用法

三、结果写入Excel表中并导出

我引入的是Openyxl库
引入代码:

import openpyxl as op

具体代码:

	ws = op.Workbook()
    wb = ws.active
    //定义表的列名
    wb.cell(row=1, column=1, value='Url')
    wb.cell(row=1, column=2, value='Username')
    //在指定表格写入内容
    wb.cell(row=count, column=1, value=f'https://github.com/{url}?tab=repositories')
    wb.cell(row=count, column=2, value=url)
    //文件保存到对应路径
    ws.save("用户链接信息.xlsx")

总结

Python爬虫感觉比Java爬虫相对简单,功能很强大,有很多库,引入就好。Python爬虫还有很多的框架比如Scrapy等,但是这里的问题很简单就不用到这个了,有兴趣的可以去了解一下。

希望对大家有用!

你可能感兴趣的:(python,爬虫,开发语言)