爬取目标

1.本次代码是在python2上运行通过的,python3的最需改2行代码,用到其它python模块

  • selenium 2.53.6 +firefox 44
  • BeautifulSoup
  • requests

2.爬取目标网站,我的博客:https://home.cnblogs.com/u/yoyoketang

爬取内容:爬我的博客的所有粉丝的名称,并保存到txt

3.由于博客园的登录是需要人机验证的,所以是无法直接用账号密码登录,需借助selenium登录

selenium获取cookies

1.大前提:先手工操作浏览器,登录我的博客,并记住密码

(保证关掉浏览器后,下次打开浏览器访问我的博客时候是登录状态)

2.selenium默认启动浏览器是一个空的配置,默认不加载配置缓存文件,这里先得找到对应浏览器的配置文件地址,以火狐浏览器为例

3.使用driver.get_cookies()方法获取浏览器的cookies

# coding:utf-8
import requests
from selenium import webdriver
from bs4 import BeautifulSoup
import re
import time
# firefox浏览器配置文件地址
profile_directory = r'C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles\yn80ouvt.default'
# 加载配置
profile = webdriver.FirefoxProfile(profile_directory)
# 启动浏览器配置
driver = webdriver.Firefox(profile) driver.get("https://home.cnblogs.com/u/yoyoketang/followers/") time.sleep(3)
cookies = driver.get_cookies() # 获取浏览器cookies
print(cookies)
driver.quit()

(注:要是这里脚本启动浏览器后,打开的博客页面是未登录的,后面内容都不用看了,先检查配置文件是不是写错了)

requests添加登录的cookies

1.浏览器的cookies获取到后,接下来用requests去建一个session,在session里添加登录成功后的cookies

s = requests.session()  # 新建session

# 添加cookies到CookieJar
c = requests.cookies.RequestsCookieJar()
for i in cookies:
c.set(i["name"], i['value']) s.cookies.update(c) # 更新session里cookies

计算粉丝数和分页总数

1.由于我的粉丝的数据是分页展示的,这里一次只能请求到45个,所以先获取粉丝总数,然后计算出总的页数

# 发请求
r1 = s.get("https://home.cnblogs.com/u/yoyoketang/relation/followers") soup = BeautifulSoup(r1.content, "html.parser") # 抓取我的粉丝数
fensinub = soup.find_all(class_="current_nav")
print fensinub[0].string
num = re.findall(u"我的粉丝\((.+?)\)", fensinub[0].string)
print u"我的粉丝数量:%s"%str(num[0]) # 计算有多少页,每页45条
ye = int(int(num[0])/45)+1
print u"总共分页数:%s"%str(ye)

保存粉丝名到txt

# 抓取第一页的数据
fensi = soup.find_all(class_="avatar_name")
for i in fensi:
name = i.string.replace("\n", "").replace(" ","")
print name
with open("name.txt", "a") as f: # 追加写入
f.write(name.encode("utf-8")+"\n") # 抓第二页后的数据
for i in range(2, ye+1):
r2 = s.get("https://home.cnblogs.com/u/yoyoketang/relation/followers?page=%s"%str(i))
soup = BeautifulSoup(r1.content, "html.parser")
# 抓取我的粉丝数
fensi = soup.find_all(class_="avatar_name") for i in fensi:
name = i.string.replace("\n", "").replace(" ","")
print name
with open("name.txt", "a") as f: # 追加写入
f.write(name.encode("utf-8")+"\n")

参考代码:

# coding:utf-8
import requests
from selenium import webdriver
from bs4 import BeautifulSoup
import re
import time # firefox浏览器配置文件地址
profile_directory = r'C:\Users\admin\AppData\Roaming\Mozilla\Firefox\Profiles\yn80ouvt.default' s = requests.session() # 新建session
url = "https://home.cnblogs.com/u/yoyoketang" def get_cookies(url):
'''启动selenium获取登录的cookies'''
try:
# 加载配置
profile = webdriver.FirefoxProfile(profile_directory)
# 启动浏览器配置
driver = webdriver.Firefox(profile)
driver.get(url+"/followers") time.sleep(3)
cookies = driver.get_cookies() # 获取浏览器cookies
print(cookies)
driver.quit()
return cookies
except Exception as msg:
print(u"启动浏览器报错了:%s" %str(msg))
def add_cookies(cookies):
'''往session添加cookies'''
try:
# 添加cookies到CookieJar
c = requests.cookies.RequestsCookieJar()
for i in cookies:
c.set(i["name"], i['value']) s.cookies.update(c) # 更新session里cookies
except Exception as msg:
print(u"添加cookies的时候报错了:%s" % str(msg)) def get_ye_nub(url):
'''获取粉丝的页面数量'''
try:
# 发请求
r1 = s.get(url+"/relation/followers")
soup = BeautifulSoup(r1.content, "html.parser")
# 抓取我的粉丝数
fensinub = soup.find_all(class_="current_nav")
print(fensinub[0].string)
num = re.findall(u"我的粉丝\((.+?)\)", fensinub[0].string)
print(u"我的粉丝数量:%s"%str(num[0])) # 计算有多少页,每页45条
ye = int(int(num[0])/45)+1
print(u"总共分页数:%s"%str(ye))
return ye
except Exception as msg:
print(u"获取粉丝页数报错了,默认返回数量1 :%s"%str(msg))
return 1 def save_name(nub):
'''抓取页面的粉丝名称'''
try:
# 抓取第一页的数据
if nub <= 1:
url_page = url+"/relation/followers"
else:
url_page = url+"/relation/followers?page=%s" % str(nub)
print(u"正在抓取的页面:%s" %url_page)
r2 = s.get(url_page, verify=False)
soup = BeautifulSoup(r2.content, "html.parser")
fensi = soup.find_all(class_="avatar_name")
for i in fensi:
name = i.string.replace("\n", "").replace(" ","")
print(name)
with open("name.txt", "a") as f: # 追加写入
f.write(name.encode("utf-8")+"\n") # python3的改成下面这两行
# with open("name.txt", "a", encoding="utf-8") as f: # 追加写入
# f.write(name+"\n") except Exception as msg:
print(u"抓取粉丝名称过程中报错了 :%s"%str(msg)) if __name__ == "__main__":
cookies = get_cookies(url)
add_cookies(cookies)
n = get_ye_nub(url)
for i in list(range(1, n+1)):
save_name(i)

---------------------------------python接口自动化完整版-------------------------

全书购买地址 https://yuedu.baidu.com/ebook/585ab168302b3169a45177232f60ddccda38e695

作者:上海-悠悠 QQ交流群:588402570

也可以关注下我的个人公众号:

python+selenium+requests爬取我的博客粉丝的名称的更多相关文章

  1. python3+selenium3+requests爬取我的博客粉丝的名称

    爬取目标 1.本次代码是在python3上运行通过的 selenium3 +firefox59.0.1(最新) BeautifulSoup requests 2.爬取目标网站,我的博客:https:/ ...

  2. python+selenium+requests爬取qq空间相册时遇到的问题及解决思路

    最近研究了下用python爬取qq空间相册的问题,遇到的问题及解决思路如下: 1.qq空间相册的访问需要qq登录并且需是好友,requests模块模拟qq登录略显麻烦,所以采用selenium的dri ...

  3. Python爬虫小实践:爬取任意CSDN博客所有文章的文字内容(或可改写为保存其他的元素),间接增加博客访问量

    Python并不是我的主业,当初学Python主要是为了学爬虫,以为自己觉得能够从网上爬东西是一件非常神奇又是一件非常有用的事情,因为我们可以获取一些方面的数据或者其他的东西,反正各有用处. 这两天闲 ...

  4. Scrapy爬取自己的博客内容

    python中常用的写爬虫的库有urllib2.requests,对于大多数比较简单的场景或者以学习为目的,可以用这两个库实现.这里有一篇我之前写过的用urllib2+BeautifulSoup做的一 ...

  5. python+selenium+bs4爬取百度文库内文字 && selenium 元素可以定位到,但是无法点击问题 && pycharm多行缩进、左移

    先说一下可能用到的一些python知识 一.python中使用的是unicode编码, 而日常文本使用各类编码如:gbk utf-8 等等所以使用python进行文字读写操作时候经常会出现各种错误, ...

  6. 开发记录_自学Python写爬虫程序爬取csdn个人博客信息

    每天刷开csdn的博客,看到一整个页面,其实对我而言,我只想看看访问量有没有上涨而已... 于是萌生了一个想法: 想写一个爬虫程序把csdn博客上边的访问量和评论数都爬下来. 打算通过网络各种搜集资料 ...

  7. python+selenium+PhantomJS爬取网页动态加载内容

    一般我们使用python的第三方库requests及框架scrapy来爬取网上的资源,但是设计javascript渲染的页面却不能抓取,此时,我们使用web自动化测试化工具Selenium+无界面浏览 ...

  8. python+selenium+xpath 爬取天眼查工商基本信息

    # -*- coding:utf-8 -*-# author: kevin# CreateTime: 2018/8/16# software-version: python 3.7 import ti ...

  9. 看我怎么扒掉CSDN首页的底裤(python selenium+phantomjs爬取CSDN首页内容)

    这里只是学习一下动态加载页面内容的抓取,并不适用于所有的页面. 使用到的工具就是python selenium和phantomjs,另外调试的时候还用了firefox的geckodriver.exe. ...

随机推荐

  1. requests中获取请求到文本编码格式

    1.使用requests模块: import requests 2.通过网络请求,并获取到数据 url = "http://www.stat-nba.com/award/item14.htm ...

  2. Python中if __name__ == "__main__"详解

       比如你编写一个test.py文件,一个python文件就可以看作是一个python的模块,这个python模块(.py文件)有两种使用方式:直接运行使用和作为模块被其他模块调用.   解释下__ ...

  3. HPU :字符串的统计

    字符串的统计 时间限制: 2 Sec 内存限制: 128 MB提交: 15 解决: 1 题目描述 给定n个字符串,我想知道第i个字符串已经出现多少次? 输入 第一行输入一个整数t,代表t(t < ...

  4. 定义一组抽象的 Awaiter 的实现接口,你下次写自己的 await 可等待对象时将更加方便

    我在几篇文章中都说到了在 .NET 中自己实现 Awaiter 情况.async / await 写异步代码用起来真的很爽,就像写同步一样.然而实现 Awaiter 没有现成的接口,它需要你按照编译器 ...

  5. CTF-练习平台-Misc之 Linux基础1

    十四.Linux基础1 下载打开文件,解压后发下是一个没有后缀名的文件,添加后缀名为txt,搜索关键词“KEY”,发现flag Linux???不存在的!

  6. C语言指针和操作系统的逻辑地址

    你在进行C语言指针编程中,可以读取指针变量本身值(&操作),实际上这个值就是逻辑地址,它是相对于你当前进程数据段的地址,不和绝对物理地址相干.只有在Intel实模式下,逻辑地址才和物理地址相等 ...

  7. drill 集成开源s3 存储minio

    drill 支持s3数据的查询,同时新版的通过简单配置就可以实现minio 的集成 测试使用docker 运行drill 参考 https://www.cnblogs.com/rongfenglian ...

  8. 如何判断一个请求是否为AJAX请求

    普通请求与ajax请求的报文头不一样,通过如下 String requestType = request.getHeader("X-Requested-With");  如果req ...

  9. c++从string类型转换为bool类型

    利用输入字符串流istringstream bool b; string s="true"; istringstream(s)>>boolalpha>>b; ...

  10. java关键字,保留字

    Java语言有51个保留关键字,其中const和goto虽然被保留但未被使用.你不能使用保留关键字来命名类.方法或变量. 一.保留关键字 数据类型: Boolean   int   long   sh ...