美文网首页
爬虫学习(requests+BeautifulSoup)

爬虫学习(requests+BeautifulSoup)

作者: kkjusdoit | 来源:发表于2019-11-25 22:13 被阅读0次

[转]用python爬虫保存美国农业部网站上的水果【证件照】(点击阅读原文)

对爬取内容兴趣不大,主要是学习一下爬虫requests+BeautifulSoup库的使用,以及学习这钟编程形式。(毕竟自己写的。。。毫无章法)

首先导入必要的库
import requests
from bs4 import BeautifulSoup
#指定下载文件夹
IMG_FOLDER = 'C://Users//Administrator//Desktop//'
每条数据的HTML元素布局
一一对应
eg
div.document
dl.defList
难点:CSS选择器soup.select()

在 Tag 或 BeautifulSoup 对象的 .select() 方法中传入字符串参数, 即可使用CSS选择器的语法找到tag:


soup.select
run函数
def run():
    for (idx, page) in enumerate(range(360)):
        resp = requests.get(
                'https://usdawatercolors.nal.usda.gov/pom/search.xhtml?start={}&searchText=&searchField=&sortField='.format(idx*20))
        soup = BeautifulSoup(resp.text, 'html.parser')  #Python标准库解析器
         #选择div.document(包含页面中所有水果元素),并一一迭代
        for (div_idx, div) in enumerate(soup.select('div.document')): 
            doc = div.select_one('dl.defList')  #选择单个水果的全部元素
            #接下来选择dd a标签,并一一获取元素
            artist = doc.select('dd a')[0].get_text() 
            year =  doc.select('dd a')[1].get_text()
            #找不到名字就用none代替
            scientific_name = 'none' if doc.select('dd a')[2] is None else  doc.select('dd a')[2].get_text()
            common_name = 'none' if doc.select('dd a')[3] is None else  doc.select('dd a')[3].get_text()
            thumb_pic_src = div.select_one('img')['src']
            id = (idx + 1) * 20 + div_idx +1
            info =FruitInfo(id, artist, year, scientific_name, common_name, thumb_pic_src)    #创建类实例
            print(info)  #会调用__str__魔术方法
            info.download_and_save() #实例调用方法
类(包括下载保存、图片链接转换等)
class FruitInfo:
    #创建带有特定初始状态的自定义实例,数据属性--实例属性
    def __init__(self, id, artist, year, scientific_name, common_name, thumb_pic_url):
        self.id = id
        self.artist= artist
        self.year = year
        self.scientific_name = scientific_name
        self.common_name = common_name
        self.thumb_pic_url = thumb_pic_url
    #方法--实例属性
    def download_and_save(self):
        filename = '{}-{}-{}-{}.png'.format(self.id, self.common_name, self.year, self.artist).replace(' ','_')
        print('filename=', filename)
        ori_img_url = self.__parse_ori_img_url()
        print('original img url =',ori_img_url)
        resp = requests.get(ori_img_url)
        with open(IMG_FOLDER+filename,'wb') as f:
            f.write(resp.content)
            print('saved...',filename)
    # ->用于指示函数返回的类型(str类型)。
    def __parse_ori_img_url(self) ->str:
        img_id = self.thumb_pic_url.split('/')[2]
        print('img id = ',img_id)
        return 'https://usdawatercolors.nal.usda.gov/pom/download.xhtml?id={}'.format(img_id)
    #见下文注释
    def __str__(self):
        return 'FruitInfo(artist={},year={},scientific_name={},common_name={},thumb_pic_url={})'.format(self.artist,
                                                                                                        self.year,
                                                                                                        self.scientific_name,
                                                                                                       self.common_name,self.thumb_pic_url)


知识点:object._str _(self)
通过 str(object) 以及内置函数 format()print() 调用以生成一个对象的“非正式”或格式良好的字符串表示。返回值必须为一个 字符串 对象。

启动run()
if __name__ == '__main__':
    run()

知识点:What does the if name == "main": do?

  • name 是当前模块名,当模块被直接运行时模块名为 main 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行;当模块是被导入时,代码块不被运行。

相关文章

网友评论

      本文标题:爬虫学习(requests+BeautifulSoup)

      本文链接:https://www.haomeiwen.com/subject/vatswctx.html