Beautifulsoup4

Beautifulsoup简介

Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.你可能在寻找 Beautiful Soup3 的文档,Beautiful Soup3 目前已经停止开发,官网推荐在现在的项目中使用Beautiful Soup 4, 移植到BS4

一、安装

pip install bs4

1.1解析器

Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。

pip install lxml

1.2 解析器对比

主要的解析器优缺点

解析器 使用方法 优势 劣势
Python标准库 BeautifulSoup(markup, "html.parser") Python的内置标准库 执行速度适中 文档容错能力强 Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
lxml HTML 解析器 BeautifulSoup(markup, "lxml") 速度快 文档容错能力强 需要安装C语言库
lxml XML 解析器 BeautifulSoup(markup, ["lxml", "xml"]) BeautifulSoup(markup, "xml") 速度快 唯一支持XML的解析器 需要安装C语言库
html5lib BeautifulSoup(markup, "html5lib") 最好的容错性 以浏览器的方式解析文档 生成HTML5格式的文档 速度慢 不依赖外部扩展

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

需要熟悉前端基础

整体方法论

from bs4 import BeautifulSoup
1. 页面源代码
2. soup = BeautifulSoup(页面源代码,解释器)
soup.find("div", attrs={属性:值}).find().find_all().find()
soup.find_all("div", attrs={属性:值})

二、BeautifulSoup参数

关于bs4, 本质上我们知道两个东西就好, 一个是find,另一个是find_all, 从名字上看. 一个是查找一个, 另一个是查找所有.

# 含义
1. find, 在页面中查找一个结果, 找到了就返回
2. find_all, 在页面中查找一堆结果. 找完了才返回

# 语法
find(标签, attrs={属性:值})
find_all(标签, attrs={属性:值})

css选择器来获取页面内容

1. select_one(选择器)  使用`选择器`获取html文档中的标签, 拿一个
2. select(选择器) 使用`选择器`获取html文档中的标签, 拿一堆

三、Beautifulsoup使用

一、beautifulsoup的简单使用

2、快速开始

下面的一段HTML代码将作为例子被多次用到.这是 爱丽丝梦游仙境的 的一段内容(以后内容中简称为 爱丽丝 的文档):

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml')
# html进行美化
print(soup.prettify())

匹配代码

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The Dormouse's story
   </b>
  </p>
  <p class="story">
   Once upon a time there were three little sisters; and their names were
   <a class="sister" href="http://example.com/elsie" id="link1">
    Elsie
   </a>
   ,
   <a class="sister" href="http://example.com/lacie" id="link2">
    Lacie
   </a>
   and
   <a class="sister" href="http://example.com/tillie" id="link3">
    Tillie
   </a>
   ;
and they lived at the bottom of a well.
  </p>
  <p class="story">
   ...
  </p>
 </body>
</html>

几个简单的浏览结构化数据的方法:

soup.title  # 获取标签title
# <title>The Dormouse's story</title>

soup.title.name   # 获取标签名称
# 'title'

soup.title.string   # 获取标签title内的内容
# 'The Dormouse's story'

soup.title.parent  # 获取父级标签

soup.title.parent.name  # 获取父级标签名称
# 'head'

soup.p
# <p class="title"><b>The Dormouse's story</b></p>

soup.p['class']  # 获取p的class属性值
# 'title'

soup.a
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find(id="link3")  # 获取id为link3的标签
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

从文档中找到所有<a>标签的链接:

for link in soup.find_all('a'):
    print(link.get('href'))
    # http://example.com/elsie
    # http://example.com/lacie
    # http://example.com/tillie

从文档中获取所有文字内容:

print(soup.get_text())

3、如何使用

将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄.

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"))

soup = BeautifulSoup("<html>data</html>", 'lxml')

然后,Beautiful Soup选择最合适的解析器来解析这段文档,如果手动指定解析器那么Beautiful Soup会选择指定的解析器来解析文档。

二、beautifulsoup的遍历文档树

还拿”爱丽丝梦游仙境”的文档来做例子:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
    <body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
# lxml和html.parser解析的有时候会根据html是否完整而有解析不同的问题,需要注意
soup = BeautifulSoup(html_doc, 'html.parser')

通过这段例子来演示怎样从文档的一段内容找到另一段内容

1、子节点

一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性.

注意: Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点。

1.1 .contents

tag的 .contents 属性可以将tag的子节点以列表的方式输出:

head_tag = soup.head
head_tag
# <head><title>The Dormouse's story</title></head>

head_tag.contents
[<title>The Dormouse's story</title>]

title_tag = head_tag.contents[0]
title_tag
# <title>The Dormouse's story</title>
title_tag.contents
# [u'The Dormouse's story']

字符串没有 .contents 属性,因为字符串没有子节点:

text = title_tag.contents[0]
text.contents
# AttributeError: 'NavigableString' object has no attribute 'contents'

2、 节点内容

2.1 .string

如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。

通俗点说就是:如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。例如:

print (soup.head.string)
#The Dormouse's story
# <title><b>The Dormouse's story</b></title>
print (soup.title.string)
#The Dormouse's story

如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None

print (soup.html.string)
#None

2.2 .text

如果tag包含了多个子节点, text则会返回内部所有文本内容

print (soup.html.text)

注意:

strings和text都可以返回所有文本内容

区别:text返回内容为字符串类型 strings为生成器generator

3、 多个内容

.strings .stripped_strings 属性

3.1.strings

获取多个内容,不过需要遍历获取,比如下面的例子:

for string in soup.strings:
    print(repr(string))
    
    
'''
  '\n'
"The Dormouse's story"
'\n'
'\n'
"The Dormouse's story"
'\n'
'Once upon a time there were three little sisters; and their names were\n'
'Elsie'
',\n'
'Lacie'
' and\n'
'Tillie'
';\nand they lived at the bottom of a well.'
'\n'
'...'
'\n'  
    
'''    

3.2 .stripped_strings

输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容

for string in soup.stripped_strings:
    print(repr(string))


'''

"The Dormouse's story"
"The Dormouse's story"
'Once upon a time there were three little sisters; and their names were'
'Elsie'
','
'Lacie'
'and'
'Tillie'
';\nand they lived at the bottom of a well.'
'...'

'''

4、 父节点

继续分析文档树,每个tag或字符串都有父节点:被包含在某个tag中

4.1 .parent

通过 .parent 属性来获取某个元素的父节点.在例子“爱丽丝”的文档中,<head>标签是<title>标签的父节点:

title_tag = soup.title
title_tag
# <title>The Dormouse's story</title>
title_tag.parent
# <head><title>The Dormouse's story</title></head>

文档的顶层节点比如<html>的父节点是 BeautifulSoup 对象:

html_tag = soup.html
type(html_tag.parent)
# <class 'bs4.BeautifulSoup'>

三、beautifulsoup的搜索文档树

1、find_all

find_all( name , attrs , recursive , string , **kwargs )

find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件:

soup.find_all("title")
# [<title>The Dormouse's story</title>]

soup.find_all("a")
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find_all(id="link2")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
# 模糊查询 包含sisters的就可以
soup.find(string=re.compile("sisters"))
# 'Once upon a time there were three little sisters; and their names were\n'

有几个方法很相似,还有几个方法是新的,参数中的 stringid 是什么含义? 为什么 find_all("p", "title") 返回的是CSS Class为”title”的<p>标签? 我们来仔细看一下 find_all() 的参数.

1.1 name 参数

name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.

简单的用法如下:

soup.find_all("title")
# [<title>The Dormouse's story</title>]

搜索 name 参数的值可以使任一类型的 过滤器 ,字符串,正则表达式,列表,方法或是 True .

1 传字符串

最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签

soup.find_all('b')
# [<b>The Dormouse's story</b>]

2.传正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到

import re
for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b

3. 传列表

3.1如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签

soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

1.2 keyword 参数

如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.

soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
# 超链接包含elsie标签
print(soup.find_all(href=re.compile("elsie")))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
# 以The作为开头的字符串
print(soup.find_all(text=re.compile("^The"))) 
# ["The Dormouse's story", "The Dormouse's story"]
# class选择器包含st的节点
print(soup.find_all(class_=re.compile("st")))

搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True .

下面的例子在文档树中查找所有包含 id 属性的tag,无论 id 的值是什么:

soup.find_all(id=True)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

使用多个指定名字的参数可以同时过滤tag的多个属性:

soup.find_all(href=re.compile("elsie"), id='link1')
# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以

print(soup.find_all("a", class_="sister"))

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
]

'''

通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:

data_soup.find_all(attrs={"data-foo": "value"})
# [<div data-foo="value">foo!</div>]

注意:如何查看条件id和class同时存在时的写法

print(soup.find_all('b', class_="story", id="x"))
print(soup.find_all('b', attrs={"class":"story", "id":"x"}))

1.3 text 参数

通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True

import re

print(soup.find_all(text="Elsie"))
# ['Elsie']

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
# ['Elsie', 'Lacie', 'Tillie']

# 只要包含Dormouse就可以
print(soup.find_all(text=re.compile("Dormouse")))
# ["The Dormouse's story", "The Dormouse's story"]

1.4 limit 参数

find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

print(soup.find_all("a",limit=2))
print(soup.find_all("a")[0:2])

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
'''

2、find()

find( name , attrs , recursive , string , **kwargs )

find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个<body>标签,那么使用 find_all() 方法来查找<body>标签就不太合适, 使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.下面两行代码是等价的:

soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]

soup.find('title')
# <title>The Dormouse's story</title>

唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.

find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .

print(soup.find("nosuchtag"))
# None

soup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:

soup.head.title
# <title>The Dormouse's story</title>

soup.find("head").find("title")
# <title>The Dormouse's story</title>

四、beautifulsoup的css选择器

我们在写 CSS 时,标签名不加任何修饰,类名前加点,id名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 *soup.select(),*返回类型是 *list*

1、通过标签名查找

print(soup.select("title"))  #[<title>The Dormouse's story</title>]
print(soup.select("b"))      #[<b>The Dormouse's story</b>]

2、通过类名查找

print(soup.select(".sister")) 

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

'''

3、id名查找

print(soup.select("#link1"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

4、组合查找

组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开

print(soup.select("p #link2"))

#[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

直接子标签查找

print(soup.select("p > #link2"))
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

查找既有class也有id选择器的标签

a_string = soup.select(".story#test")

查找有多个class选择器的标签

a_string = soup.select(".story.test")

查找有多个class选择器和一个id选择器的标签

a_string = soup.select(".story.test#book")

5、属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print(soup.select("a[href='http://example.com/tillie']"))
#[<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容:

for title in soup.select('a'):
    print (title.get_text())

'''
Elsie
Lacie
Tillie
'''

四、案列一(图片案列)

from bs4 import BeautifulSoup
import requests
import time
from urllib.parse import urljoin


url = 'https://desk.zol.com.cn/pc/'

header = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36"
}

resp = requests.get(url, headers=header)

# 转换编码
resp.encoding = 'gbk'
resp_text = resp.text

# html.parser 解释器
main_page = BeautifulSoup(resp_text, "html.parser")

# 查找到列表取下面的所有a标签
a_list = main_page.find("ul", attrs={"class": "pic-list2"}).find_all("a")

# 循环取出href地址
for i in a_list:
    href = i.get("href")
    # 判断exe去除
    if href.endswith(".exe"):
        continue

    text = i.find("em").text

    href = urljoin(url, href)
    # print(href + text)

    good = requests.get(href, headers=header)
    good.encoding = 'gbk'
    good_list = good.text

    b_list = BeautifulSoup(good_list, "html.parser")
    x_list = b_list.find("img", attrs={"id": "bigImg"}).get("src")
    print(x_list)

    # 下载图片
    img_resp = requests.get(x_list)
    file_name = x_list.split("/")[-1]

    with open(f'tupian/{file_name}','wb') as w:
        w.write(img_resp.content)
    time.sleep(1)

五、案列二(图片案列)

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin


url = "https://desk.zol.com.cn/pc/"
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36"
}
# 发送请求, 获取页面源代码
resp = requests.get(url, headers=headers)
resp.encoding = 'gbk'  # 设置一下字符集
# 1. 创建BeautifulSoup的对象
main_soup = BeautifulSoup(resp.text, "html.parser")
# 2. 找到超链接, 请注意.这里面的属性拼接,多少会和页面稍微有一些细微的差别.
a_list = main_soup.select("ul.pic-list2 a")
# 3. 循环出每一个超链接
for a in a_list:
    # 4.1 拿到href, 也就是子页面的url
    href = a.get("href")
    # 4.2 获取超链接中的文本信息
    content = a.text
    print("没啥用,只是给你演示如何获取文本", content)
    # 5. 剔除特殊项
    if href.endswith(".exe"):  # 垃圾客户端. 坑我
        continue
    # 6. 域名拼接
    href = urljoin(url, href)

    # 7. 剩下的就是套娃了
    child_resp = requests.get(href, headers=headers)
    child_resp.encoding = 'gbk'
    child_soup = BeautifulSoup(child_resp.text, "html.parser")
    # print(child_resp.text)  # 适当的打印,可以帮助你调BUG
    img = child_soup.select_one("#bigImg")
    img_src = img.get("src")

    # 下载图片
    img_resp = requests.get(img_src, headers=headers)
    file_name = img_src.split("/")[-1]
    with open(file_name, mode="wb") as f:
        f.write(img_resp.content)
    print("下载完一张图片了")

六、案例三(图片面向对象案例)

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import time


class Spider:
    def __init__(self, url):
        self.url = url
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
            'Cookie': 'z_pro_city=s_provice%3Dshanghai%26s_city%3Dshanghai; userProvinceId=2; userCityId=0; userCountyId=0; userLocationId=26; ip_ck=5cGI4v33j7QuMjY5NTcwLjE3MTk5OTA2NjE%3D; lv=1719990661; vn=1; Hm_lvt_ae5edc2bc4fc71370807f6187f0a2dd0=1719990662; z_day=icnmo11564%3D1%26ixgo20%3D1; Adshow=5; Hm_lpvt_ae5edc2bc4fc71370807f6187f0a2dd0=1719993763; questionnaire_pv=1719964806'
        }

    def get_html(self, url):
        response = requests.get(url, headers=self.headers, stream=True)
        response.raise_for_status()
        response.encoding = 'gbk'
        return response.text

    def get_soup(self, url):
        htmls = self.get_html(url)
        soups = BeautifulSoup(htmls, 'lxml')
        main_soup = soups.find("ul", attrs={"class": "pic-list2"}).find_all("a")
        return main_soup

    def get_page(self, url):
        htmls = self.get_html(url)
        soups = BeautifulSoup(htmls, 'lxml')
        big_img = soups.find("img", attrs={"id": "bigImg"}).get("src")
        return big_img


if __name__ == '__main__':
    spider = Spider(url='https://desk.zol.com.cn/pc/')

    html = spider.get_html(spider.url)
    soup = spider.get_soup(spider.url)

    for item in soup:
        href = item.get('href')

        if href.endswith('.exe'):
            continue
        img_url = urljoin(spider.url, href)

        test = item.find("em").text
        # 图片页面
        page_url = spider.get_page(img_url)
        print(page_url)
        # 下载图片
        img_resp = requests.get(page_url, headers=spider.headers, stream=True)
        file_name = page_url.split("/")[-1]
        print(file_name)
        with open(f'tu/{file_name}', 'wb') as w:
            w.write(img_resp.content)
        time.sleep(1)

七、案例三(图片面向对象案例)

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import os


class Spider:
    def __init__(self, url):
        self.url = url
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
        }

    def get_html(self, url):
        response = requests.get(url, headers=self.headers, stream=True)
        response.raise_for_status()
        response.encoding = 'gbk'  # 根据页面实际编码设置
        return response.text

    def get_image_urls(self, url):
        html = self.get_html(url)
        soup = BeautifulSoup(html, 'lxml')
        image_links = []
        for item in soup.find("ul", attrs={"class": "pic-list2"}).find_all("a"):
            href = item.get('href')
            if href.endswith('.exe'):
                continue
            img_url = urljoin(self.url, href)
            image_links.append(img_url)
        return image_links

    def get_image_url_from_page(self, page_url):
        page_html = self.get_html(page_url)
        page_soup = BeautifulSoup(page_html, 'lxml')
        big_img_url = page_soup.find("img", attrs={"id": "bigImg"})
        if big_img_url:
            return big_img_url.get("src")
        return None

    def download_image(self, image_url, save_path):
        response = requests.get(image_url, headers=self.headers, stream=True)
        response.raise_for_status()
        file_name = image_url.split("/")[-1]
        file_path = os.path.join(save_path, file_name)
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        with open(file_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        print(f"Downloaded {file_path}")

    def run(self):
        image_page_urls = self.get_image_urls(self.url)
        save_path = 'tu/'
        for page_url in image_page_urls:
            image_url = self.get_image_url_from_page(page_url)
            if image_url:
                self.download_image(image_url, save_path)


if __name__ == '__main__':
    spider = Spider(url='https://desk.zol.com.cn/pc/')
    spider.run()

posted @ 2022-05-19 13:07  沈忻凯  阅读(70)  评论(0)    收藏  举报