1. 发送web请求

1.1  requests

  用requests库的get()方法发送get请求,常常会添加请求头"user-agent",以及登录"cookie"等参数

1.1.1  user-agent

  登录网站,将"user-agent"值复制到文本文件

1.1.2  cookie

  登录网站,将"cookie"值复制到文本文件

1.1.3  测试代码

import requests
from requests.exceptions import RequestException headers = {
'cookie': '',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
} # 替换为自己的cookie def get_page(url):
try:
html = requests.get(url, headers=headers, timeout=5)
if html.status_code == 200:
print('请求成功')
return html.text
else: # 这个else语句不是必须的
return None
except RequestException:
print('请求失败') if __name__ == '__main__':
input_url = 'https://www.zhihu.com/hot'
get_page(input_url)

1.2  selenium

  多数网站能通过window.navigator.webdriver的值识别selenium爬虫,因此selenium爬虫首先要防止网站识别selenium模拟浏览器。同样,selenium请求也常常需要添加请求头"user-agent",以及登录"cookie"等参数

1.2.1  移除Selenium中window.navigator.webdriver的值

  在程序中添加如下代码(对应老版本谷歌)

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
time.sleep(10)

1.2.2  user-agent

  登录网站,将"user-agent"值复制到文本文件,执行如下代码将添加请求头

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions option = ChromeOptions()
option.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')

1.2.3  cookie

  因为selenium要求cookie需要有"name","value"两个键以及对应的值的值,如果网站上面的cookie是字符串的形式,直接复制网站的cookie值将不符合selenium要求,可以用selenium中的get_cookies()方法获取登录"cookie"

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import time
import json option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')
driver = Chrome(options=option)
time.sleep(10) driver.get('https://www.zhihu.com/signin?next=%2F')
time.sleep(30)
driver.get('https://www.zhihu.com/')
cookies = driver.get_cookies()
jsonCookies = json.dumps(cookies) with open('cookies.txt', 'a') as f: # 文件名和文件位置自己定义
f.write(jsonCookies)
f.write('\n')

1.2.4  测试代码示例

  将上面获取到的cookie复制到下面程序中便可运行

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import time option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
time.sleep(10) driver.get('https://www.zhihu.com')
time.sleep(10) driver.delete_all_cookies() # 清除刚才的cookie
time.sleep(2) cookie = {} # 替换为自己的cookie
driver.add_cookie(cookie)
driver.get('https://www.zhihu.com/')
time.sleep(5)
for i in driver.find_elements_by_css_selector('div[itemprop="zhihu:question"] > a'):
print(i.text)

2. HTML解析(元素定位)

  要爬取到目标数据首先要定位数据所属元素,BeautifulSoup和selenium都很容易实现对HTML的元素遍历

2.1  BeautifulSoup元素定位

  下面代码BeautifulSoup首先定位到属性为"HotItem-title"的"h2"标签,然后再通过.text()方法获取字符串值

import requests
from requests.exceptions import RequestException headers = {
'cookie': '',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
} # 替换为自己的cookie def get_page(url):
try:
html = requests.get(url, headers=headers, timeout=5)
if html.status_code == 200:
print('请求成功')
return html.text
else: # 这个else语句不是必须的
return None
except RequestException:
print('请求失败') def parse_page(html):
html = BeautifulSoup(html, "html.parser")
titles = html.find_all("h2", {'class': 'HotItem-title'})[:10]
for title in titles:
print(title.text()) if __name__ == '__main__':
input_url = 'https://www.zhihu.com/hot'
parse_page(get_page(input_url))

2.2  selenium元素定位

  selenium元素定位语法形式与requests不太相同,下面代码示例(1.2.4 测试代码示例)采用了一种层级定位方法:'div[itemprop="zhihu:question"] > a',笔者觉得这样定位比较放心。

  selenium获取文本值得方法是.text,区别于requests的.text()

from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import time option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
time.sleep(10) driver.get('https://www.zhihu.com')
time.sleep(10) driver.delete_all_cookies() # 清除刚才的cookie
time.sleep(2) cookie = {} # 替换为自己的cookie
driver.add_cookie(cookie)
driver.get('https://www.zhihu.com/')
time.sleep(5)
for i in driver.find_elements_by_css_selector('div[itemprop="zhihu:question"] > a'):
print(i.text)

  

爬虫:HTTP请求与HTML解析(爬取某乎网站)的更多相关文章

  1. python爬虫学习之使用BeautifulSoup库爬取开奖网站信息-模块化

    实例需求:运用python语言爬取http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html这个开奖网站所有的信息,并且保存为txt文件和excel文件. 实 ...

  2. Python开发爬虫之BeautifulSoup解析网页篇:爬取安居客网站上北京二手房数据

    目标:爬取安居客网站上前10页北京二手房的数据,包括二手房源的名称.价格.几室几厅.大小.建造年份.联系人.地址.标签等. 网址为:https://beijing.anjuke.com/sale/ B ...

  3. scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250

    scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大 ...

  4. 爬虫简单之二---使用进程爬取起点中文网的六万多也页小说的名字,作者,等一些基本信息,并存入csv中

    爬虫简单之二---使用进程爬取起点中文网的六万多也页小说的名字,作者,等一些基本信息,并存入csv中 准备使用的环境和库Python3.6 + requests + bs4 + csv + multi ...

  5. 另类爬虫:从PDF文件中爬取表格数据

    简介   本文将展示一个稍微不一样点的爬虫.   以往我们的爬虫都是从网络上爬取数据,因为网页一般用HTML,CSS,JavaScript代码写成,因此,有大量成熟的技术来爬取网页中的各种数据.这次, ...

  6. Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(人人网)(下)

    Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(下) 自动使用cookie的方法,告别手动拷贝cookie http模块包含一些关于cookie的模块,通过他们我们可以自动的使用co ...

  7. (java)selenium webdriver爬虫学习--爬取阿里指数网站的每个分类的top50 相关数据;

    主题:java 爬虫--爬取'阿里指数'网站的每个分类的top50 相关数据: 网站网址为:http://index.1688.com/alizs/top.htm?curType=offer& ...

  8. [Python]爬取 游民星空网站 每周精选壁纸(1080高清壁纸) 网络爬虫

    一.检查 首先进入该网站的https://www.gamersky.com/robots.txt页面 给出提示: 弹出错误页面 注: 网络爬虫:自动或人工识别robots.txt,再进行内容爬取 约束 ...

  9. python爬虫(三) 用request爬取拉勾网职位信息

    request.Request类 如果想要在请求的时候添加一个请求头(增加请求头的原因是,如果不加请求头,那么在我们爬取得时候,可能会被限制),那么就必须使用request.Request类来实现,比 ...

  10. 爬虫黑科技,我是怎么爬取indeed的职位数据的

    最近在学习nodejs爬虫技术,学了request模块,所以想着写一个自己的爬虫项目,研究了半天,最后选定indeed作为目标网站,通过爬取indeed的职位数据,然后开发一个自己的职位搜索引擎,目前 ...

随机推荐

  1. css字体的属性

    1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="U ...

  2. Apache Pulsar 在能源互联网领域的落地实践

    关于 Apache Pulsar Apache Pulsar 是 Apache 软件基金会顶级项目,是下一代云原生分布式消息流平台,集消息.存储.轻量化函数式计算为一体,采用计算与存储分离架构设计,支 ...

  3. Hi3516如何连接Wifi(二)

    目录: 一.总体思路 二.启动Daemon 三.作者文章合集 书承上回(Hi3516如何连接Wifi(一)),上一篇聊了一下怎样在Hi3516中用wpa_supplicant连接到Wifi热点,本文讲 ...

  4. java 基础知识储备

    初始JAVA JAVA 帝国的诞生 1972年C诞生 贴近硬件,运行极快,效率极高. 操作系统,编译器,数据库,网络系统等 指针和内存管理 1982年C++诞生 面向对象 兼容C 图形领域.游戏等 纵 ...

  5. java面试一日一题:rabbitMQ的工作模式

    问题:请讲下rabbitMQ的工作模式 分析:该问题纯属概念题,需要掌握rabbtiMQ的基础知识,同时该题也是切入MQ的一个引子: 回答要点: 主要从以下几点去考虑, 1.rabbitMQ的基本概念 ...

  6. ASP.NET网页开发基础(7)

    整理了一点的小知识点: 1.ASP.NET网页扩展名:    .asax 全局应用程序类的扩展名     .xml 访问网页时的扩展名     .htm     .ascx Web用户控件的扩展名   ...

  7. 前端 JS 问题记录

    立即执行函数 !function(){}() function 前面增加符号 ! ~ + - 之类,都是告诉浏览器自动执行这个匿名函数,因为这些符号的运算级别都是高的 (function(){... ...

  8. 【笔记】《Redis设计与实现》chapter16 Sentinel

    16.1 启动并初始化Sentinel 初始化服务器 Sentinel本质上只是运行在特殊模式下的Redis服务器,启动第一步就是初始化一个普通的Redis服务器 使用Sentinel专用代码 使用r ...

  9. Spring(11) - Introductions进行类扩展方法

    Introductions(引用),在 Aspect 中称为类型间的声明,使切面能够声明被通知的对象(拦截的对象)实现给定的接口,并提供该接口的实现. 简单点说可以将一个类的实现方法复制到未实现的类中 ...

  10. Day05_19_方法回顾

    方法回顾 * 静态方法 和 非静态方法 1.静态方法属于类所有,类实例化前即可使用: 2.非静态方法可以访问类中的任何成员,静态方法只能访问类中的静态成员: 3.因为静态方法会在类加载的时候就进行初始 ...