python从入门到精通(十二):python爬虫的进阶使用

python爬虫分析

4种python的爬虫的不同写法

1.基于requests库的方法
requests是Python的一个HTTP客户端库,用于发送HTTP请求和处理响应。它提供了简洁的API,使得发送HTTP请求和处理响应变得非常简单。你可以使用requests库获取网页内容,然后配合解析库(如BeautifulSoup、lxml等)进行HTML或XML文档的解析。

2.基于Scrapy框架的方法
Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。它可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。Scrapy提供了丰富的API和工具,可以方便地实现网页请求、数据提取、数据存储等操作。

3.基于Selenium库的方法
Selenium是一个用于Web应用程序测试的工具,但它同样可以用于爬取动态生成的网页内容。Selenium可以模拟真实用户操作浏览器,包括点击、输入、滚动等操作,从而获取JavaScript渲染后的网页内容。

4.基于urllib库的方法
urllib是Python内置的HTTP请求库,它可以用来打开和读取URL。虽然urllib的功能比requests库要弱一些,但在一些简单的场景下,使用urllib就足够了。

第二种:基于requests库的方法

1.requests模块的作用:

发送http请求,获取响应数据,requests 库是一个原生的 HTTP 库,比 urllib 库更为容易使用。requests 库发送原生的 HTTP 1.1 请求,无需手动为 URL 添加查询串, 也不需要对 POST 数据进行表单编码。相对于 urllib 库, requests 库拥有完全自动化 Keep-alive 和 HTTP 连接池的功能。

2.requests模块

pip/pip3 install requests

Request 基本请求方式


你可以通过 requests 库发送所有的http请求:

requests.get("http://httpbin.org/get") #GET请求
requests.post("http://httpbin.org/post") #POST请求
requests.put("http://httpbin.org/put") #PUT请求
requests.delete("http://httpbin.org/delete") #DELETE请求
requests.head("http://httpbin.org/head") #HEAD请求
requests.options("http://httpbin.org/OPTIONS") #OPTIONS请求

3.requests模块发送get请求

GET 参数说明:res = requests.get(url,headers=headers,params,timeout)

• url:要抓取的 url 地址。

• headers:用于包装请求头信息。

• params:请求时携带的查询字符串参数。

• timeout:超时时间,超过时间会抛出异常。

# 1.2.1-简单的代码实现
import requests 
# 目标url
url = 'https://www.baidu.com' 
# 向目标url发送get请求
response = requests.get(url)
# 打印响应网页内容
print(response.text)

3.1 text获取响应的网页内容

返回字符串类型数据

# 1.2.2-response.content
import requests 
# 向目标url发送get请求
response = requests.get('https://www.baidu.com' )
# 打印响应内容
print(response.text)

3.2 content获取响应的网页内容

返回 bytes 类型数据,decode返回的也是字符串效果等同于response.text

# 1.2.2-response.content
import requests 
# 向目标url发送get请求
response = requests.get('https://www.baidu.com' )
# 打印响应内容
print(response.content) # 注意这里!
# 通过对response.content进行decode,来解决中文乱码
print(response.content.decode()) # 注意这里!
response.content.decode() 默认utf-8
response.content.decode("GBK")
常见的编码字符集

utf-8
gbk
gb2312
ascii (读音:阿斯克码)
iso-8859-1

3.3 反爬添加 headers 的请求

访问豆瓣不添加header会报错,被识别为爬虫

import requests
url = 'https://movie.douban.com/top250'
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=header)
print(response.text)

3.4 获取请求响应状态码

print(response.status_code)

3.5 url发送带参数的请求

爬取动态网页时我们需要传递不同的参数获取 不同的内容;GET 传递参数有两种方法,可以直接在链接中添加参数或者利用 params 添加参数

import requests
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit
/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
url = 'https://search.douban.com/movie/subject_search?search_text=肖申克的救赎'
response = requests.get(url, headers=headers)
print(response.text)

3.6 通过 params 携带参数字典

需要把请求的关键存在字典变量里,发送请求的时候带上字典,参数字典设置给

import requests
headers = {
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
# 这是目标url
url = 'https://search.douban.com/movie/subject_search?'
# 请求参数是一个字典
kw = {'search_text': '肖申克的救赎'}
# 带上请求参数发起请求,获取响应
response = requests.get(url, headers=headers, params=kw)
print(response.text)

3.7 调用json() 方法

如果我们访问之后获得的数据是JSON格式的,那么我们可以使用json方法,直接获取转换成宁典格式的数据。
但是需要注意的是,如果返回的结果不是JSON格式,便会出现解析错误,抛出异常!

import requests
response = requests.get("http://httpbin.org/get")
print(response.text)
print(response.json())
print(type(response. json()))

3.8 参数中携带cookie

网站经常利用请求头中的 Cookie 字段来做用户访问状态的保持,那么我们可以在 headers 参数中添加 Cookie ,模拟普通用户的请求。

可以先获取网站cookie

import requests
url = 'https://movie.douban.com/'
response = requests.get(url)
print(response.cookies)
#print(r.cookies.items())
# 响应的cookies
for key, value in response.cookies.items():
    print(f"{key} = {value}")
    import requests

在使用cookie访问登录后网站内容

import requests
import re
# 构造请求头字典
headers = {
# 从浏览器中复制过来的User-Agent
    "user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
# 从浏览器中复制过来的Cookie
    "cookie": 'bid = Mx0Pmwb-qI8'
}
# 请求头参数字典中携带cookie字符串
response = requests.get('https://www.douban.com/doumail/', headers=headers)
data = re.findall('<div id="content">(.*?)<h1>(.*?)</h1>',response.text)
print(response.status_code)
print(data)

通过cookies参数来设置,将cookies构造字典传入cookies字段

import requests
url = "'https://user.qzone.qq.com/这里写上要登录的QQ号/infocenter'"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
}
cookies={"Cookie":"123456789"}
r = requests.get(url, headers=headers,cookies=cookies)
print(r.text)

3.9 超时时间过短将会报错

requests.get(url,timeout = 0.1) #备注时间为0.001

3.10 原始响应内容

import requests
response = requests.get("http://httpbin.org/get")
print(response.raw)

3.11 指定响应字符编码

print(response.encoding)  # 查看响应字符编码
response.encoding="utf-8"    #更改为utf-8编码

3.12 重定向allow_redirects

在网络请求中,通常都会存在重定向问题,在Requests中是默认开启允许重定向的,如果存在重定向时,自动继续跟随访问

import requests
response = requests.get("http://httpbin.org/get",allow_redirects=False)

3.13 查看响应的url

import requests
response = requests.get("http://httpbin.org/get")
print(response.url)

3.14 服务器返回的cookies

import requests
response = requests.get("http://httpbin.org/get")
print(response.cookies)

3.15查看响应的headers头

import requests
response = requests.get("http://httpbin.org/get")
print(response.headers)

4. requests模块发送POST请求

post(url, data=None, json=None, **kwargs):

import requests
payload = {"username": "admin", "password": "123456"}
#response = requests.post("http://httpbin.org/post", data={'usernaem':'admin'}
response = requests.post("http://httpbin.org/post", data=payload)
print(response.text)

4.1 POST 请求抓取网页

import requests
# 准备翻译的数据
wd =input("请输入要搜索的关键字:")
wd = {"search_text": wd}
# 准备伪造请求
headers = {
# User-Agent:首字母大写,表示请求的身份信息;一般直接使用浏览器的身份信息,伪造爬虫请求
# 让浏览器认为这个请求是由浏览器发起的[隐藏爬虫的信息]
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.41"
}
# 发送POST请求,附带要翻译的表单数据--以字典的方式进行传递
response = requests.post("https://search.douban.com/movie/subject_search?", data=wd)
print(response.url)
# 打印返回的数据
# print(response.content)
print(response.content.decode("utf-8"))
# print(response.text.encode("utf-8"))

4.2 使用Session维持登录信息

import requests
import re
# 构造请求头字典
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
}
# 实例化session对象
session = requests.session()
# 访问登陆页获取登陆请求所需参数
response = session.get('https://github.com/login', headers=headers)
authenticity_token = re.search('name="authenticity_token" value="(.*?)" />',response.text).group(1)  # 使用正则获取登陆请求所需参数
# 构造登陆请求参数字典
data = {
'commit': 'Sign in', # 固定值
'utf8': ' ', # 固定值
'authenticity_token': 'authenticity_token', # 该参数在登陆页的响应内容中
'login':input('输入github账号:'),
'password':input('输入github账号:')
}
# 发送登陆请求(无需关注本次请求的响应)
session.post('https://github.com/session', headers=headers, data=data)
# 打印需要登陆后才能访问的页面
response = session.get('https://github.com/settings/profile', headers=headers)
print(response.text)
from requests import sessions
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',

    }
session = sessions.Session()
response = session.get("https://www.baidu.com/s?wd=python",headers=headers)
print(response.text)
# or
# requests = sessions.Session()
# response = requests.get("https://www.baidu.com/s", params={"wd": "python"})

print(u"请求的URL: ", response.request.url)
print(u"请求的参数(GET方法专属): ", response.request.path_url)
print(u"请求的Method: ", response.request.method)
print(u"请求的头: ", response.request.headers)

print(u"响应状态码: ", response.status_code)
print(u"响应头: ", response.headers)
print(u"响应内容: ", response.content)

print(u"请求所带的cookie和响应所返回的cookie集合: ", response.cookies)
print(u"总共耗时: ", response.elapsed)

4.2 proxies 代理参数的使用

response = requests.get (url,proxies = proxies)
#proxies 的形式:字典
proxies = {
" http ": " http :// 12.34.56.79: 9527 ",
" https ": " https :// 12.34.56.79: 9527 ",
}
import requests
proxies = {
"http": "http://124.236.111.11:80",
"https": "https:183.220.145.3:8080"
}
url= 'http://www.baidu.com'
req = requests.get(url,proxies=proxies)
print(req.status_code)

4.3 上传文件

url = 'https://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print('\n', r.text)

5.requests版的豆瓣电影top250完整版代码

from bs4 import BeautifulSoup
import re
import requests
# import urllib.request, urllib.error
import xlwt
import sqlite3

# urllib.parse模块是一个用于解析URL的工具包,支持各种对URL的操作,包括拆分、拼接、编码、解码等。
import urllib.parse


def main():
    baseurl = "https://movie.douban.com/top250?start="
    print("爬虫开始....")
    datalist = get_data(baseurl)
    save_path = r"D:\豆瓣网电影TOP250.xls"
    save_data(datalist, save_path)
    dbpath = "test1.db"
    saveData2DB(datalist,dbpath)


# 影片详情链接的规则
findLink = re.compile(r'<a href="(.*?)">')   # 创建正则表达式对象,表示规则(字符串的模式)
# 影片图片
findImgSrc = re.compile(r'<img.*src="(.*?)"',re.S)  # re.s 让换行符包含在字符中
# 影片片名
findTitle =re.compile(r'<span class="title">(.*)</span>')
# 影片评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 找到评价人数
findJudge =re.compile(r'<span>(\d*)人评价</span>')
# 找到概况
findInq =re.compile(r'<span class="inq">(.*)</span>')
# 找到影片的相关内容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
#   爬取所有网页内容
def get_data(baseurl):
    datalist = []
    # 循环爬取所有页面
    for i in range(0,10):
        url = baseurl + str(i*25)
        html = askurl(url)
        #print(html)

        # 逐一解析数据 把html使用html.parser进行解析
        soup = BeautifulSoup(html, "html.parser")

        # 引入正则表达式,匹配满足的特征的字符串
        for item in soup.find_all("div", class_="item"):   #查找符合要求的字符串,形成列表
            #print(item) #测试:查看电影item全部信息
            #break
            data = []  #用于保存所有数据
            item = str(item)
            Link = re.findall(findLink, item)[0]  # re.findall查询所有符合条件的字符串,返回一个列表
            data.append(Link)
            ImgSrc = re.findall(findImgSrc, item)[0]
            data.append(ImgSrc)
            Titles = re.findall(findTitle, item)     #片名可能只有一个中文名,没有外国名
            if (len(Titles)) == 2:
                ctitle = Titles[0]
                data.append(ctitle)             #添加中文名
                otitle = Titles[1].replace("/","")
                data.append(otitle)            #添加外国名
            else:
                data.append(Titles[0])
                data.append(" ")           #外国名字留空
            Rating = re.findall(findRating, item)[0]
            data.append(Rating)
            Judge = re.findall(findJudge, item)[0]
            data.append(Judge)
            Inq = re.findall(findInq, item)
            if (len(Inq) != 0 ):
                Inq = Inq[0].replace("。","")                     # 去掉 。
                data.append(Inq)
            else:
                data.append(" ")
            Bd = re.findall(findBd, item)[0]
            Bd = re.sub(r'<br(\s+)?/>(\s+)?',"",Bd)   # 去掉换行符<br/>
            Bd = re.sub(r'/', "", Bd)                 # 去掉 /
            data.append(Bd.strip())
            datalist.append(data)
            # print(len(datalist))
    return datalist



def save_data(datalist,save_path):
    book = xlwt.Workbook(encoding="utf-8",style_compression=0)
    sheet = book.add_sheet("豆瓣网电影TOP250",cell_overwrite_ok=True)
    col = ("电影链接","图片链接","电影中文名称","电影外语名称","电影评分","评论人数","电影概述","电影的相关内容")
    for i in range(len(col)):
        sheet.write(0,i,col[i])
    for i in range(len(datalist)):
        data = datalist[i]
        #print('爬到到第%d行了' % i)
        for j in range(len(data)):

            sheet.write(i+1, j,data[j])

    book.save(save_path)

def saveData2DB(datalist,dbpath):
    init_db(dbpath)
    conn =sqlite3.connect(dbpath)
    cur =conn.cursor()
    for data in datalist:
        for index in range(len(data)):
            if index == 4 or index ==5:
                continue
            data[index]='"'+data[index]+'"'
        sql1 ='''
                insert into movie250(info_link,pic_link,cname,ename,score,rated,instroduction,info)
                values(%s)'''% ",".join(data)
        print(sql1)
        cur.execute(sql1)
        conn.commit()
    cur.close()
    conn.close()




def init_db(dbpath):
    sql = '''
        create table movie250
        (
        id integer primary key autoincrement,
        info_link text,
        pic_link text,
        cname varchar,
        ename varchar,
        score numeric,
        rated numeric,
        instroduction text,
        info text
        )
    '''
    print(sql)
    conn = sqlite3.connect(dbpath)
    c = conn.cursor()
    c.execute(sql)
    conn.commit()
    conn.close()

# 爬取单个网页内容
def askurl(url):
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/121.0.0.0 Safari/537.36"
    }
    req = requests.get(url, headers=headers)
    try:
        html = req.content.decode('utf-8')
        # print(html)
    except requests.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    except Exception as e:
        print(e)

    return html


if __name__ == '__main__':
    main()
    # askurl('https://movie.douban.com/top250')
    print("爬虫结束")```

# python爬虫之word操作
## 安装方法
 python中常用来操作word文件的库都是使用python-docx

```python
pip install python-docx

新建文档docx

from docx import Document

document = Document()
document.save('new.docx')

doc转为docx

from win32com import client as wc
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
初级教程看:https://download.csdn.net/download/dwf1354046363/20818468 9 网络爬虫进阶之 Selenium 篇 9.1 Selenium 简介 . . . . . . . . 9.1.1 Selenium 是什么 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 9.1.2 Selenium 特点 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 9.1.3 基本安装与使用 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 9.1.4 各种浏览器驱动下载地址 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 9.1.5 Selenium 初试 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 9.2 定位元素 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 9.2.1 基本的定位方法 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 9.2.2 使用 By 定位 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 9.2.3 定位一组元素 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 9.3 控制浏览器 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 9.3.1 控制浏览器窗口大小 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 9.3.2 控制浏览器后退、前进 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 9.3.3 模拟浏览器刷新 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 9.4 WebDriver 中的常用方法 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 9.5 设置元素等待 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 9.5.1 显式等待 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 9.5.2 隐式等待 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 9.6 多表单切换 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 9.7 多窗口切换 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 9.8 其他操作 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HACKNOE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值