入门爬虫,这一篇就够了!!!

本文介绍了爬虫的基础知识,包括抓取、分析和存储三个关键步骤。讲解了urllib、requests库的使用,以及如何处理登录和反爬虫策略。还提到了分析网页内容的正则表达式、BeautifulSoup和XPath,并讨论了数据存储到文本或数据库的方法。最后,提供了Python爬虫学习资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    点击上方Python3X”,选择“置顶或者星标”

第一时间收到精彩推送!

 

有小伙伴问,新手该怎么开始学习爬虫。其实说实在的入门爬虫真的非常容易。于是我就针对如何入门爬虫进行了总结

 

爬虫三要素: 抓取、分析、存储

 

通过url进行网页的抓取,当我们请求一个网页时,先通过域名解析到对应的ip地址,然后向浏览器发送请求,建立历TCP链接,服务器返回网页的内容。再由浏览器对内容进行解析。

 

01

基础的抓取

640?wx_fmt=png

 

1

urllib 在Python2.x中我们可以通过urllib 或者urllib2 进行网页抓取,但是再Python3.x 移除了urllib2。只能通过urllib进行操作

 

 
import urllib.requestresponse = urllib.request.urlopen('https://blog.youkuaiyun.com/weixin_43499626')print(response.read().decode('utf-8'))

response = urllib.request.urlopen('https://blog.youkuaiyun.com/weixin_43499626')
print(response.read().decode('utf-8'))

 

2

requests库是一个非常实用的HTPP客户端库,是抓取操作最常用的一个库。Requests库满足很多需求

 

 
import requests# get请求response = requests.get(url='https://blog.youkuaiyun.com/weixin_43499626')  print(response.text)   #打印解码后的返回数据# 带参数的requests get请求response = requests.get(url='https://blog.youkuaiyun.com/weixin_43499626', params={'key1':'value1', 'key2':'value2'}
# get请求
response = requests.get(url='https://blog.youkuaiyun.com/weixin_43499626')  
print(response.text)   #打印解码后的返回数据
# 带参数的requests get请求
response = requests.get(url='https://blog.youkuaiyun.com/weixin_43499626', params={'key1':'value1''key2':'value2'}

 

    

02

需要登录的情况

640?wx_fmt=png

 

1

表单提交登录 向服务器发送一个post请求并携带相关参数,将服务器返回的cookie保存在本地,cookie是服务器在客户端上的“监视器”,记录了登录信息等。客户端通过识别请求携带的cookie,确定是否登录

 

 
params = {'username': 'root', 'passwd': 'root'}response = requests.post("http:xxx.com/login", data=params)for key,value in response.cookies.items():    print('key = ', key + ' ||| value :'+ value)'root''passwd''root'}
response = requests.post("http:xxx.com/login", data=params)
for key,value in response.cookies.items():
    print('key = ', key + ' ||| value :'+ value)

 

2

cookie登录 我们可以将登录的cookie存储在文件中。

 
import urllib.requestimport http.cookiejar"""保存登录的cookie""""""MozillaCookieJar : cookiejar的子类从FileCookieJar派生而来,创建与Mozilla浏览器 cookies.txt兼容的FileCookieJar实例。"""cookie = http.cookiejar.MozillaCookieJar('cookie.txt')# 构建一个cookie的处理器handler = urllib.request.HTTPCookieProcessor(cookie)# 获取一个opener对象opener = urllib.request.build_opener(handler)# # 访问携程。、获取一个请求对象request = urllib.request.Request('http://flights.ctrip.com/',headers={"Connection": "keep-alive"})# 请求服务器,获取响应对象。cookie会在response里一起响应response = opener.open(request)# 保存cookie到文件cookie.save(ignore_discard=True, ignore_expires=True)"""请求携带文件中的cookie"""import urllib.requestimport http.cookiejarcookie = http.cookiejar.MozillaCookieJar()cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)request = urllib.request.Request('http://flights.ctrip.com/')html = opener.open(request).read().decode('gbk')print(html)
import http.cookiejar
"""
保存登录的cookie
"""
"""
MozillaCookieJar : cookiejar的子类
从FileCookieJar派生而来,创建与Mozilla浏览器 cookies.txt兼容的FileCookieJar实例。
"""
cookie = http.cookiejar.MozillaCookieJar('cookie.txt')
# 构建一个cookie的处理器
handler = urllib.request.HTTPCookieProcessor(cookie)
# 获取一个opener对象
opener = urllib.request.build_opener(handler)
# # 访问携程。、获取一个请求对象
request = urllib.request.Request('http://flights.ctrip.com/',headers={"Connection""keep-alive"})
# 请求服务器,获取响应对象。cookie会在response里一起响应
response = opener.open(request)
# 保存cookie到文件
cookie.save(ignore_discard=True, ignore_expires=True)


"""
请求携带文件中的cookie
"""

import urllib.request
import http.cookiejar
cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request('http://flights.ctrip.com/')
html = opener.open(request).read().decode('gbk')

print(html)

 

 

03

遇到反爬虫怎么办?

640?wx_fmt=png

 

1

通过user-agent来控制访问, user-agent能够使服务器识别出用户的操作系统及版本、cpu类型、浏览器类型和版本。很多网站会设置user-agent白名单,只有在白名单范围内的请求才能正常访问。所以在我们的爬虫代码中需要设置user-agent伪装成一个浏览器请求。有时候服务器还可能会校验Referer,所以还可能需要设置Referer(用来标识此时的请求是从哪个页面链接过来的)

 

 
# 设置请求头信息headers = {        'Host': 'https://blog.youkuaiyun.com',        'Referer': 'https://blog.youkuaiyun.com/weixin_43499626/article/details/85875090',        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'    }response = requests.get("http://www.baidu.com", headers=headers) 
headers = {
        'Host''https://blog.youkuaiyun.com',
        'Referer''https://blog.youkuaiyun.com/weixin_43499626/article/details/85875090',
        'User-Agent''Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
response = requests.get("http://www.baidu.com", headers=headers) 

 

如下是优快云中的Request Header中的信息

 

 
accept: */*accept-encoding: gzip, deflate, braccept-language: zh-CN,zh;q=0.9content-length: 0cookie: bdshare_firstime=1500xxxxxxxx..............origin: https://blog.youkuaiyun.comreferer: https://blog.youkuaiyun.com/weixin_43499626/article/details/85875090user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36x-requested-with: XMLHttpRequest
accept-language: zh-CN,zh;q=0.9
content-length: 0
cookie: bdshare_firstime=1500xxxxxxxx..............
origin: https://blog.youkuaiyun.com
referer: https://blog.youkuaiyun.com/weixin_43499626/article/details/85875090
user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
x-requested-with: XMLHttpRequest

 

2

通过ip来限制爬虫

当我们用同一个ip多次频繁访问服务器时,服务器会检测到该请求可能是爬虫操作。因此就不能正常的响应页面的信息了。 解决办法常用的是使用IP代理池。网上就有很多提供代理的网站。

 
proxies = {  "http": "http://119.101.125.56",  "https": "http://119.101.125.1",}response = requests.get("http://www.baidu.com", proxies=random.choices(proxies)) "http""http://119.101.125.56",
  "https""http://119.101.125.1",
}
response = requests.get("http://www.baidu.com", proxies=random.choices(proxies)) 

 

3

设置请求间隔

 
import timetime.sleep(1)
time.sleep(1)

 

4

自动化测试工具Selenium Web应用程序测试的Selenium工具。该工具可以用于单元测试,集成测试,系统测试等等。它可以像真正的用户一样去操作浏览器(包括字符填充、鼠标点击、获取元素、页面切换),支持Mozilla Firefox、Google、Chrome、Safari、Opera、IE等等浏览器。

之前写过一个通过Selenium爬QQ空间的列子,点击下方超链接可查看

通过Selenium爬QQ空间

 

5

参数通过加密 某些网站可能会将参数进行某些加密,或者对参数进行拼接发送给服务器,以此来达到反爬虫的目的。这个时候我们可以试图通过js代码,查看破解的办法。 连接xxx 或者可以使用"PhantomJS",PhantomJS是一个基于Webkit的"无界面"(headless)浏览器,它会把网站加载到内存并执行页面上的JavaScript,因为不会展示图形界面,所以运行起来比完整的浏览器更高效。

 

6

 

通过robots.txt来限制爬虫

robots.txt是一个限制爬虫的规范,该文件是用来声明哪些东西不能被爬取。如果根目录存在该文件,爬虫就会按照文件的内容来爬取指定的范围。

浏览器访问https://www.taobao.com/robots.txt 可以查看淘宝的robots.txt文件 部分内容如下

 
User-agent:  BaiduspiderDisallow:  /product/Disallow:  /User-Agent:  GooglebotDisallow:  /User-agent:  BingbotDisallow:  /User-Agent:  360SpiderDisallow:  /User-Agent:  YisouspiderDisallow:  /User-Agent:  SogouspiderDisallow:  /User-Agent:  Yahoo!  SlurpDisallow:  /User-Agent:  *Disallow:  /
Disallow:  /

User-Agent:  Googlebot
Disallow:  /

User-agent:  Bingbot
Disallow:  /

User-Agent:  360Spider
Disallow:  /

User-Agent:  Yisouspider
Disallow:  /

User-Agent:  Sogouspider
Disallow:  /

User-Agent:  Yahoo!  Slurp
Disallow:  /

User-Agent:  *
Disallow:  /

 

可以看出淘宝拒绝了百度爬虫、谷歌爬虫、必应爬虫、360爬虫、神马爬虫,搜狗爬虫、雅虎爬虫等约束。

 

04

分析

640?wx_fmt=png

 

我们可以分析爬取的网页内容,获得我们真正需要的数据,常用的有正则表达式,BeautifulSoup,XPath、lxml等

正则表达式是进行内容匹配,将符合要求的内容全部获取; xpath()能将字符串转化为标签,它会检测字符串内容是否为标签,但是不能检测出内容是否为真的标签; Beautifulsoup是Python的一个第三方库,它的作用和 xpath 作用一样,都是用来解析html数据的相比之下,xpath的速度会快一点,因为xpath底层是用c来实现的

 

05

存储

640?wx_fmt=png

通过分析网页内容,获取到我们想要的数据,我们可以选择存到文本文件中,亦可以存储在数据库中,常用的数据库有MySql、MongoDB

存储为json文件

 
import jsondictObj = {    '小明':{        'age': 15,        'city': 'beijing',    },    '汤姆': {        'age': 16,        'city': 'guangzhou',    }}jsObj = json.dumps(dictObj, ensure_ascii=False)fileObject = open('jsonFile.json', 'w')fileObject.write(jsObj)fileObject.close()

dictObj = {
    '小明':{
        'age'15,
        'city''beijing',
    },
    '汤姆': {
        'age'16,
        'city''guangzhou',
    }
}

jsObj = json.dumps(dictObj, ensure_ascii=False)
fileObject = open('jsonFile.json''w')
fileObject.write(jsObj)
fileObject.close()

 

存储为cvs文件

 

 
import csvwith open('student.csv', 'w', newline='') as csvfile:    writer = csv.writer(csvfile)    writer.writerow(['姓名', '年龄', '城市'])    writer.writerows([['小明', 15 , '北京'],['汤姆', 16, '广州']])
with open('student.csv''w', newline=''as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['姓名''年龄''城市'])
    writer.writerows([['小明'15 , '北京'],['汤姆'16'广州']])

 

存储到Mongo

 

 
# mongo服务client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')# test数据库db = client.test# student表,没有自动创建student_db = db.studentstudent_json = {    'name': '小明',    'age': 15,    'city': '北京'}student_db.insert(student_json)
client = pymongo.MongoClient('mongodb://127.0.0.1:27017/')
# test数据库
db = client.test
# student表,没有自动创建
student_db = db.student
student_json = {
    'name''小明',
    'age'15,
    'city''北京'
}
student_db.insert(student_json)

 

 

 

 

文末福利,史上最全Python资料汇总(长期更新)。隔壁小孩都馋哭了 — 点击领取

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值