python3爬虫-快速入门-爬取图片和标题

直接上代码,先来个爬取豆瓣图片的,大致思路就是发送请求-得到响应数据-储存数据,原理的话可以先看看这个

https://www.cnblogs.com/sss4/p/7809821.html

import os#同来创造文件夹
import requests#发送请求和得到响应用的
from bs4 import BeautifulSoup#用来解析回应的数据

def GetHtmlText(url):#得到响应数据
    try:
        r = requests.get(url)#发送url
        r.raise_for_status()#判断是否成功
        r.encoding = ‘utf-8‘#设置编码格式
        return r.text#返回他的响应数据
    except:
        return ‘‘
def main(pages):
    filepath=os.getcwd()+‘\爬的图片\\‘#创造一个文件夹
    if not os.path.exists(filepath):#如果没有则创造
        os.makedirs(filepath)

    pagenum=pages#要爬取的页数
    fnum=1
    for page in range(pages):
        url="https://movie.douban.com/celebrity/1048000/photos/?type=C&start="+str(page*30)+‘&sortby=like&size=a&subtype=a‘#第几页
        html=GetHtmlText(url)
        soup=BeautifulSoup(html,‘html.parser‘)#html。parser是解析器
        uls=soup.find_all(‘ul‘,class_="poster-col3 clearfix")#从响应的数据中找到ul class是xxxx的数据
        for ul in uls:
            imgs=ul.find_all(‘img‘) #找到img的标签
            for img in imgs:
                imgurl=img[‘src‘]#得到img的url
                imgcontent=requests.get(imgurl).content#得到这个url下的内容content,应该是二进制的
                filename=str(fnum)+‘.jpg‘
                with open(filepath+filename,‘wb‘) as wf:#二进制形式写入数据
                    wf.write(imgcontent)
                fnum+=1

if __name__ == ‘__main__‘:
    main(9)

再来个爬去标题类的

import requests
from bs4 import BeautifulSoup

url="http://www.jianshu.com"
headers={‘User-Agent‘:‘SE 2.X MetaSr 1.0‘}#设置请求头的User-Agent,理解的话可以认为是从哪个浏览器发出的,不然的话会被反爬虫
page=requests.get(url=url,headers=headers)
page_info=page.text
page_bf=BeautifulSoup(page_info,‘html.parser‘)

#print(page_bf.prettify())
titles=page_bf.find_all(‘a‘,‘title‘)

for title in titles:
    print(title.string)
    print(‘http://www.jianshu.com‘+title.get(‘href‘))
with open(r"D:\untitled\爬虫爬到的标题.txt","w",encoding=‘utf-8‘) as file:
    for title in titles:
        file.write(title.string+‘\n‘)
        file.write("http://www.jianshu.com"+title.get(‘href‘)+‘\n\n‘)

这个是下载小说的---(别人的代码)

from bs4 import BeautifulSoup
import requests,sys
class downloader(object):
    def __init__(self):
        self.server="http://www.biqukan.com/"
        self.target="http://www.biqukan.com/1_1094"
        self.name=[]
        self.urls=[]
        self.nums=0

    def get_download_url(self):
        req=requests.get(url=self.target)
        html=req.text
        div_bf=BeautifulSoup(html)
        div=div_bf.find_all(‘div‘,class_=‘listmain‘)
        a_bf=BeautifulSoup(str(div[0]))
        a=a_bf.find_all(‘a‘)
        self.nums=len(a[15:])
        for each in a[15:]:
            self.name.append(each.string)
            self.urls.append(self.server+each.get(‘href‘))
    def get_contents(self ,target):
        req=requests.get(url=target)
        html=req.text
        bf=BeautifulSoup(html)
        texts=bf.find_all(‘div‘,class_=‘showtxt‘)
        texts=texts[0].text.replace(‘\xa0‘*8,‘\n\n‘)
        return texts
    def writer(self,name,path,text):
        write_flag=True
        with open(path,"a",encoding=‘utf-8‘) as f:
            f.write(name+‘\n‘)
            f.writelines(text)
            f.write(‘\n\n‘)

dl=downloader()
dl.get_download_url()
print("开始下载")
for i in range(dl.nums):
    dl.writer(dl.name[i], ‘一念永恒.txt‘, dl.get_contents(dl.urls[i]))
    sys.stdout.write("  已下载:%.3f%%" %  float(i/dl.nums) + ‘\r‘)
    sys.stdout.flush()
print(‘《一年永恒》下载完成‘)

原文地址:https://www.cnblogs.com/wpbing/p/9315167.html

时间: 2024-08-30 01:59:49

python3爬虫-快速入门-爬取图片和标题的相关文章

python爬虫-基础入门-爬取整个网站《3》

python爬虫-基础入门-爬取整个网站<3> 描述: 前两章粗略的讲述了python2.python3爬取整个网站,这章节简单的记录一下python2.python3的区别 python2.x 使用类库: >> urllib 库 >> urllib2 库 python3.x 使用的类库: >> urllib 库 变化: -> 在python2.x中使用import urllib2 ----- 对应的,在python3.x 中会使用import url

【Python3 爬虫】U11_爬取中国天气网

目录 1.网页分析 2.代码实现 1.网页分析 庚子年初,各种大事件不期而至,又赶上最近气温突变,所以写个爬虫来爬取下中国天气网,并通过图表反映气温最低的前20个城市. 中国天气网:http://www.weather.com.cn/textFC/hb.shtml 打开后如下图: 从图中可以看到所有城市按照地区划分了,并且每个城市都有最低气温和最高气温,通过chrome查看Elements,如下: 从上图可以看到展示当天的数据,那么<div class='conMidtab'>..这个标签则没

scrapy爬虫系列之三--爬取图片保存到本地及日志的基本用法

功能点:如何爬取图片,并保存到本地 爬取网站:斗鱼主播 完整代码:https://files.cnblogs.com/files/bookwed/Douyu.zip 主要代码: douyu.py import scrapy import json from Douyu.items import DouyuItem class DouyuSpider(scrapy.Spider): name = 'douyu' allowed_domains = ['douyucdn.cn'] base_url

爬虫---Beautiful Soup 爬取图片

上一篇简单的介绍Beautiful Soup 的基本用法,这一篇写下如何爬取网站上的图片,并保存下来 爬取图片 1.找到一个福利网站:http://www.xiaohuar.com/list-1-1.html 2.通过F12进行定位图片 3.通过下图可以看到标签为img,然后通过width="210"的属性 爬取方法 1.通过find_all()的方法进行查找图片位置 2.筛选出图片的URL和图片名称 3.筛选后会发现其中有一些图片URL不完整 4.这个时候需要在代码中加一个判断,如何

python3爬虫之入门和正则表达式

前面的python3入门系列基本上也对python入了门,从这章起就开始介绍下python的爬虫教程,拿出来给大家分享:爬虫说的简单,就是去抓取网路的数据进行分析处理:这章主要入门,了解几个爬虫的小测试,以及对爬虫用到的工具介绍,比如集合,队列,正则表达式: 用python抓取指定页面: 代码如下: import urllib.request url= "http://www.baidu.com" data = urllib.request.urlopen(url).read()# d

python爬虫---scrapy框架爬取图片,scrapy手动发送请求,发送post请求,提升爬取效率,请求传参(meta),五大核心组件,中间件

# settings 配置 UA USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36' 一丶scrapy的图片数据爬取(流数据的爬取) ? scrapy中封装好了一个管道类(ImagesPipeline),基于该管道类可以实现图片资源的请求和持久化存储 编码流程: 爬虫文件中解析出图片的地址 将

使用Scrapy爬虫框架简单爬取图片并保存本地(妹子图)

初学Scrapy,实现爬取网络图片并保存本地功能 一.先看最终效果 保存在F:\pics文件夹下 二.安装scrapy 1.python的安装就不说了,我用的python2.7,执行命令pip install scrapy,或者使用easy_install 命令都可以 2.可能会报如下错误 *********************************************************** Could not find function xmlCheckVersion in l

【Python3 爬虫】14_爬取淘宝上的手机图片

现在我们想要使用爬虫爬取淘宝上的手机图片,那么该如何爬取呢?该做些什么准备工作呢? 首先,我们需要分析网页,先看看网页有哪些规律 打开淘宝网站http://www.taobao.com/ 我们可以看到左侧是主题市场,将鼠标移动到[女装/男装/内衣]这一栏目,我们可以看到更细类的展示 假如我们现在需要爬取[羽绒服],那么我们进入到[羽绒服]衣服这个界面 此时查看浏览器地址,我们可以看到 网址复制到word或者其他地方会发生url转码 我们可以选中[羽绒服模块的第1,2,3页进行网址对比],对比结果

python3爬虫-使用requests爬取起点小说

import requests from lxml import etree from urllib import parse import os, time def get_page_html(url): '''向url发送请求''' resoponse = session.get(url, headers=headers, timeout=timeout) try: if resoponse.status_code == 200: return resoponse except Except