Day 10 10.1 数据解析方法之-BS4

BS4

【1】简介

  • 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:

    '''
    Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。
    它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
    '''
  • Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.你可能在寻找 Beautiful Soup3 的文档,Beautiful Soup 3 目前已经停止开发,官网推荐在现在的项目中使用Beautiful Soup 4。

官方文档: https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

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

    pip3 install lxml
  • 另一个可供选择的解析器是纯Python实现的 html5lib , html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

    pip3 install html5lib
  • 简单使用:

    • 从一个soup对象开始,以下两种方式生成一个soup对象

      from bs4 import BeautifulSoup
      soup = BeautifulSoup(open("index.html"))    ##传入文件
      soup = BeautifulSoup("<html>data</html>")   ##文本

      构造soup对象时,可以传入解析器参数,如果不传入的话,会以最好的方式去解析

  • 下面的一段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, 'html.parser')
  • 从文档中找到所有标签的链接:

    for link in soup.find_all('a'):
        print(link.get('href'))
    • 从文档中获取所有文字内容:

      print(soup.get_text())

【2】四种对象

  • Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种BeautifulSoupTag , NavigableString , Comment

    • tag对象,同网页中的标签的意思
    from bs4 import 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>
    """
    
    # 一、查找tag对象
    soup = BeautifulSoup(html_doc, 'html.parser')
    print(soup.head, type(soup.head))
    print(soup.title, type(soup.title))
    print(soup.a, type(soup.a))  # 第一个a标签,如果想获取所有a标签要用到soup.find_all('a')
    print(soup.p.b)
    
    # 二、查找tag对象的标签名和属性
    print(soup.a.name)  # a
    print(soup.p.b.name)  # b
    print(soup.a["href"])
    print(soup.a.attrs)
    
    '''
    三、
    HTML 4定义了一系列可以包含多个值的属性.在HTML5中移除了一些,却增加更多.
    最常见的多值的属性是 class (一个tag可以有多个CSS的class). 
    还有一些属性 rel , rev , accept-charset , headers , accesskey . 
    在Beautiful Soup中多值属性的返回类型是list
    '''
    
    print(soup.a["class"])  # 返回列表
    
    # 四、tag的属性可以被添加,删除或修改(tag的属性操作方法与字典一样)
    # soup.a["class"] = ["sister c1"]
    # del soup.a["id"]
    # print(soup)
    
    # 五、获取标签对象的文本内容
    print(soup.p.string)  # p下的文本只有一个时,取到,否则为None
    print(soup.p.strings)  # 拿到一个生成器对象, 取到p下所有的文本内容
    for i in soup.p.strings:
        print(i)
    # 如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None,如果只有一个子节点那么就输出该子节点的文本,比如下面的这种结构,soup.p.string 返回为None,但soup.p.strings就可以找到所有文本
    p2 = soup.find_all("p")[1]
    print(p2.string)
    print(p2.strings)
    for i in p2.strings:
        print(i)
    # text 和 string
    print(soup.p.string)
    print(soup.p.text)  # 取到p下所有的文本内容,text属性更常用,并且它可以直接过滤掉注释
    print(p2.text)
  • 这种情况下,会产生Comment对象

    markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
    soup = BeautifulSoup(markup,"html.parser")
    comment = soup.b.string
    print(comment)
    print(type(comment))
  • 结果为:

    Hey, buddy. Want to buy a used parser?
    <class 'bs4.element.Comment'>

我们可以看到这时候.string返回的对象不再是bs4.element.NavigableString,而是Comment

【3】遍历文档树(导航文档树)

from bs4 import 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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

# 1、嵌套选择
print(soup.head.title.text)
print(soup.body.a.text)

# 2、子节点、子孙节点
print(soup.p.contents)  # p下所有子节点
print(soup.p.children)  # 得到一个迭代器,包含p下所有子节点

for i, child in enumerate(soup.p.children, 1):
    print(i, child)

print(soup.p.descendants)  # 获取子孙节点,p下所有的标签都会选择出来
for i, child in enumerate(soup.p.descendants, 1):
    print(i, child)
for i, child in enumerate(soup.find_all("p")[1].descendants, 1):
    print(i, child)

# 3、父节点、祖先节点
print(soup.a.parent)  # 获取a标签的父节点
print(soup.a.parent.text)  # 获取a标签的父节点
print(soup.a.parents)  # 找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

# 4、兄弟节点
print("===")
print(soup.a.next_sibling)  # 下一个兄弟,类型:<class 'bs4.element.NavigableString'>
print(soup.a.next_sibling.next_sibling)
print(soup.a.previous_sibling.previous_sibling)
print(soup.a.previous_siblings)  # 上面的兄弟们=>生成器对象

【4】搜索文档树

  • recursive 是否从当前位置递归往下查询,如果不递归,只会查询当前soup文档的子元素
  • string 这里是通过tag的内容来搜索,并且返回的是类容,而不是tag类型的元素
  • **kwargs 自动拆包接受属性值,所以才会有soup.find_all('a',id='title') ,id='title'为**kwargs自动拆包掺入

BeautifulSoup定义了很多搜索方法,这里着重介绍2个: find() 和 find_all() .其它方法的参数和用法类似

参数列表解读

(1)find_all

find_all( name , attrs , recursive , string , **kwargs )
  • name参数
soup = BeautifulSoup(html_doc, 'lxml')

# 一、 name 四种过滤器: 字符串、正则表达式、列表、方法
# 1、字符串:即标签名
print(soup.find_all(name='a'))

# 2、正则表达式

print(soup.find_all(name=re.compile('^b')))  # 找出b开头的标签,结果有body和b标签

# 3、列表:如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签:
print(soup.find_all(name=['a', 'b']))


# 4、方法:如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
def has_class_but_no_id(tag):
    return tag.has_attr('class') and tag.has_attr('id')


print(soup.find_all(name=has_class_but_no_id))
  • keyword 参数

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

print(soup.find_all(href="http://example.com/tillie"))
print(soup.find_all(href=re.compile("^http://")))
print(soup.find_all(id=True)) # 拥有id属性的tag
print(soup.find_all(href=re.compile("http://"), id='link1') # 多个属性
print(soup.find_all("a", class_="sister")) # 注意,class是Python的关键字,所以class属性用class_
print(soup.find_all("a",attrs={"href": re.compile("^http://"), "id": re.compile("^link[12]")}))      
# 通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:
data_soup.find_all(attrs={"data-foo": "value"})
  • text参数
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"]
  • limit参数

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

print(soup.find_all("a",limit=2))
  • recursive 参数

调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False

(2)find

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

find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个标签,那么使用 find_all() 方法来查找标签就不太合适, 使用 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 .

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>

(3)其它方法

#(1) find_parents() 和 find_parent()
a_string = soup.find(text="Lacie")
print(a_string)  # Lacie

print(a_string.find_parent())
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
print(a_string.find_parents())
print(a_string.find_parent("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>

'''

# (2)find_next_siblings() 和 find_next_sibling()
'''
这2个方法通过 .next_siblings 属性对当tag的所有后面解析的兄弟tag节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点, find_next_sibling() 只返回符合条件的后面的第一个tag节点.
'''

first_link = soup.a

print(first_link.find_next_sibling("a"))
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>

print(first_link.find_next_siblings("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_previous_siblings() 和 find_previous_sibling()的使用类似于find_next_sibling和find_next_siblings。

# (3)find_all_next() 和 find_next()
'''
这2个方法通过 .next_elements 属性对当前tag的之后的tag和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点: 
'''
first_link = soup.a
print(first_link.find_all_next(string=True))
# ['Elsie', ',\n', 'Lacie', ' and\n', 'Tillie', ';\nand they lived at the bottom of a well.', '\n', '...', '\n']
print(first_link.find_next(string=True)) # Elsie

# find_all_previous() 和 find_previous()的使用类似于find_all_next() 和 find_next()。

【5】Css选择器

select

css选择器的方法为select(css_selector)
目前支持的选择器如下案例,css选择器可以参考https://www.w3school.com.cn/cssref/css_selectors.ASP

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

soup.select("p nth-of-type(3)")
# [<p class="story">...</p>]

soup.select("body 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.select("html head title")
# [<title>The Dormouse's story</title>]


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

soup.select("p > 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.select("p > a:nth-of-type(2)")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

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

soup.select("body > a")

soup.select("#link1 ~ .sister")
# [<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.select("#link1 + .sister")
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]


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>]

soup.select("[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>]

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

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


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


soup.select('a[href]')
# [<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.select('a[href="http://example.com/elsie"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

soup.select('a[href^="http://example.com/"]')
# [<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.select('a[href$="tillie"]')
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.select('a[href*=".com/el"]')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
multilingual_markup = """
 <p lang="en">Hello</p>
 <p lang="en-us">Howdy, y'all</p>
 <p lang="en-gb">Pip-pip, old fruit</p>
 <p lang="fr">Bonjour mes amis</p>
"""
multilingual_soup = BeautifulSoup(multilingual_markup)
multilingual_soup.select('p[lang|=en]')
# [<p lang="en">Hello</p>,
#  <p lang="en-us">Howdy, y'all</p>,
#  <p lang="en-gb">Pip-pip, old fruit</p>]
select_one

返回查找到的元素的第一个

【6】解析流程

1.实例化一个BeautifulSoup的对象

  • 实例化一个BeautifulSoup的对象,然后把即将被解析的页面源码数据加载到该对象中
    • BeautifulSoup(fp,'lxml'):fp表示本地的一个文件,该种方式是将本地存储的html文件进行数据解析
    • BeautifulSoup(page_text,'lxml'):page_text是网络请求到的页面源码数据,该种方式是直接将网络请求到的页面源码数据进行数据解析

2.调用BeautifulSoup对象

  • 调用BeautifulSoup对象中相关的属性和方法实现标签定位和数据提取

3.具体解析操作详解

  • 在当前目录下新建一个test.html文件,然后将下述内容拷贝到该文件中

    <html lang="en">
    <head>
    	<meta charset="UTF-8" />
    	<title>测试bs4</title>
    </head>
    <body>
    	<div>
    		<p>百里守约</p>
    	</div>
    	<div class="song">
    		<p>李清照</p>
    		<p>王安石</p>
    		<p>苏轼</p>
    		<p>柳宗元</p>
    		<a href="http://www.song.com/" title="赵匡胤" target="_self">
    			<span>this is span</span>
    		宋朝是最强大的王朝,不是军队的强大,而是经济很强大,国民都很有钱</a>
    		<a href="" class="du">总为浮云能蔽日,长安不见使人愁</a>
    		<img src="http://www.baidu.com/meinv.jpg" alt="" />
    	</div>
    	<div class="tang">
    		<ul>
    			<li><a href="http://www.baidu.com" title="qing">清明时节雨纷纷,路上行人欲断魂,借问酒家何处有,牧童遥指杏花村</a></li>
    			<li><a href="http://www.163.com" title="qin">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</a></li>
    			<li><a href="http://www.126.com" alt="qi">岐王宅里寻常见,崔九堂前几度闻,正是江南好风景,落花时节又逢君</a></li>
    			<li><a href="http://www.sina.com" class="du">杜甫</a></li>
    			<li><a href="http://www.dudu.com" class="du">杜牧</a></li>
    			<li><b>杜小月</b></li>
    			<li><i>度蜜月</i></li>
    			<li><a href="http://www.haha.com" id="feng">凤凰台上凤凰游,凤去台空江自流,吴宫花草埋幽径,晋代衣冠成古丘</a></li>
    		</ul>
    	</div>
    </body>
    </html>
  • 有了test.html文件后,在练习如下操作

    from bs4 import BeautifulSoup
    #fp就表示本地存储的一个html文件
    fp = open('./test.html','r',encoding='utf-8')
    #解析本地存储的html文件中的内容
    #实例化BeautifulSoup对象,然后把即将被解析的页面源码数据加载到了该对象中
    soup = BeautifulSoup(fp,'lxml') #参数2,lxml是固定形式,表示指定的解析器
    #标签定位
    #方式1:soup.tagName,只会定位到符合条件的第一个标签
    tag1 = soup.title #定位到了title标签
    tag2 = soup.div
    #方式2:属性定位,find函数,findall函数
        #find('tagName',attrName='attrValue'):find只会定位到满足要的第一个标签
    tag3 = soup.find('div',class_='song')#定位class属性值为song的div标签
    tag4 = soup.find('a',id='feng')#定位id属性值为feng的a标签
        #findAll('tagName',attrName='attrValue'):可以定位到满足要求的所有标签
    tag5 = soup.findAll('div',class_='song')
    #方式3:选择器定位:soup.select('选择器')
        #id选择器:#feng  ----id为feng
        #class选择器:.song ----class为song
        #层级选择器:大于号表示一个层级,空格表示多个层级
    tag6 = soup.select('#feng') #定位到所有id属性值为feng的标签
    tag7 = soup.select('.song')#定位到所有class属性值为song的标签
    tag8 = soup.select('.tang > ul > li') #定位到了class为tang下面的ul下面所有的li标签
    tag9 = soup.select('.tang li')
    
    #提取标签中的内容
    #1.提取标签中间的内容:
        #tag.string:只可以提取到标签中直系的文本内容
        #tag.text:可以提取到标签中所有的文本内容
    # p_tag = soup.p
    # print(p_tag.string)
    # print(p_tag.text)
    # div_tag = soup.find('div',class_='song')
    # print(div_tag.text)
    
    #2.提取标签的属性值
        #tag['attrName']
    img_tag = soup.img
    print(img_tag['src']) #提取img标签的src的属性值

【7】练习

  • 使用bs4爬取豆瓣电影排行榜信息
from bs4 import BeautifulSoup
soup = BeautifulSoup(s, 'html.parser')

s=soup.find_all(class_="item")
for item in s:
  print(item.find(class_="pic").a.get("href"))
  print(item.find(class_="pic").em.string)
  print(item.find(class_="info").contents[1].a.span.string)
        print(item.find(class_="info").contents[3].contents[3].contents[3].string)
        print(item.find(class_="info").contents[3].contents[3].contents[7].string)

【8】案例集锦

1、小说批量爬取

  • url:https://www.shicimingju.com/book/sanguoyanyi.html

  • 需求:将每一个章节的标题和内容进行爬取然后存储到一个文件中

    • 步骤:

      • 1.请求主页的页面源码数据
      • 2.数据解析:
        • 章节标题
        • 章节详情页的链接
      • 3.解析章节详细内容
      • 4.将解析的章节标题和内容进行存储
      from bs4 import BeautifulSoup
      import requests
      headers = {
          'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
      }
      #首页地址
      main_url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
      #发起请求,获取了主页页面源码
      response = requests.get(url=main_url,headers=headers)
      response.encoding = 'utf-8'
      page_text = response.text
      #数据解析:章节标题+详情页链接
      soup = BeautifulSoup(page_text,'lxml')
      a_list = soup.select('.book-mulu > ul > li > a')
      fp = open('./sanguo.txt','w',encoding='utf-8')
      for a in a_list:
          title = a.string #章节标题
          detail_url = 'https://www.shicimingju.com'+a['href'] #详情页地址
          #请求详情页的页面源码数据
          response = requests.get(url=detail_url,headers=headers)
          response.encoding = 'utf-8'
          detail_page_text = response.text
          #解析:解析章节内容
          d_soup = BeautifulSoup(detail_page_text,'lxml')
          div_tag = d_soup.find('div',class_='chapter_content')
          content = div_tag.text #章节内容
          fp.write(title+':'+content+'\n')
          print(title,'爬取保存成功!')
      fp.close()

2、代理批量爬取

  • url:https://www.kuaidaili.com/free

  • 需求:将前5页的所有id和port解析且存储到文件中

    • 爬取单页内容
    #只爬取了第一页的内容
    from bs4 import BeautifulSoup
    import requests
    headers = {
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
    }
    url = 'https://www.kuaidaili.com/free'
    page_text = requests.get(url=url,headers=headers).text
    soup = BeautifulSoup(page_text,'lxml')
    trs = soup.select('tbody > tr')
    for tr in trs:
        t1 = tr.findAll('td')[0]
        t2 = tr.findAll('td')[1]
        ip = t1.string
        port = t2.string
        print(ip,port)
    • 爬取多页内容
    #爬取多页内容
    from bs4 import BeautifulSoup
    import requests
    import time
    headers = {
        'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
    }
    #爬取多页
    #1.创建一个通用的url(可以变换成任意页码的url)
    url = 'https://www.kuaidaili.com/free/inha/%d/'
    #2.通过循环以此生成不同页码的url
    for page in range(1,11):
        print('----------正在爬取第%d页的数据!-----------'%page)
        #format用来格式化字符串的(不可以修改url这个字符串本身)
        new_url = format(url%page)
        #循环发送每一页的请求
        #注意:get方法是一个阻塞方法!
        page_text = requests.get(url=new_url,headers=headers).text
        time.sleep(1)
        soup = BeautifulSoup(page_text,'lxml')
        trs = soup.select('tbody > tr')
        for tr in trs:
            t1 = tr.findAll('td')[0]
            t2 = tr.findAll('td')[1]
            ip = t1.string
            port = t2.string
            print(ip,port)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值