最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python爬蟲,獲取,解析,存儲詳解

 更新時間:2021年10月08日 09:10:01   作者:萬能守恒定律  
這篇文章主要介紹了Python爬蟲獲取、解析,獲數(shù)據(jù)操作,其中代碼描述非常詳細(xì),需要的朋友可以參考下,希望能夠給你帶來幫助

1.獲取數(shù)據(jù)

import requests
def drg(url):
    try:
        head ={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/\
       537.36 (KHTML, like Gecko) Chrome/\
       91.0.4472.164 Safari/537.36'}
        r = requests.get(url,headers=head)
        r.raise_for_status()  # 如果狀態(tài)不是200,引發(fā)HTTPError異常
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "產(chǎn)生異常"
url = "https://www.ip138.com/mobile.asp?mobile=13018305773&action=mobile"
print(drg(url))

2.解析數(shù)據(jù)

import requests
def login():
    try:
        # 登錄之后界面的url
        urllogin="http://www.cqooc.com/user/login?username=12608199000635&password=48C032612C2A6777D28A969307B52127E198D59AA78522943C1B283CF7B89E69&nonce=6BA36BBB1F623279&cnonce=8257070573EFE28F"
        s=requests.session()
        r=s.post(urllogin,data=Form,headers=headers)
        r.encoding = r.apparent_encoding
        r.raise_for_status()
        return s
    except Exception as error:
        print(error)
def get_html(s,url):
    try:
        r=s.get(url,headers=headers)
        r.encoding = r.apparent_encoding
        r.raise_for_status()
        return r.text
    except Exception as error:
        print(error)
if __name__=="__main__":
    # 登錄之后的界面user-agent
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36",
    }
    # 跟著自己的改變
    Form = {
        "username": "12608199000635",
        "password": "48C032612C2A6777D28A969307B52127E198D59AA78522943C1B283CF7B89E69",
        "nonce": "6BA36BBB1F623279",
        "cnonce": "8257070573EFE28F"
    }
    lin=login()
    # 個人中心的網(wǎng)址
    url="http://www.cqooc.com/my/learn"
    html=get_html(lin,url)
    print(html)

3.數(shù)據(jù)保存為CSV格式和存入數(shù)據(jù)庫

保存為CSV

import  requests
from lxml import etree
import csv
#獲取數(shù)據(jù)
def get_html(url,time=30):
    try:
        r = requests.get(url, timeout=time)
        r.encoding = r.apparent_encoding
        r.raise_for_status()
        return r.text
    except Exception as error:
        print(error)
def parser(html): #解析函數(shù)
    doc=etree.HTML(html) #html轉(zhuǎn)換為soup對象
    out_list=[] #解析函數(shù)輸出數(shù)據(jù)的列表
    #二次查找法
    for row in  doc.xpath("http://*[@class='book-img-text']//li/*[@class='book-mid-info']"):
        row_data=[
            row.xpath("h4/a/text()")[0], #書名
            row.xpath("p[@class='author']/a/text()")[0], #作者
            row.xpath("p[2]/text()")[0].strip(), #介紹
            row.xpath("p[@class='update']/span/text()")[0] #更新日期
        ]
        out_list.append(row_data) #將解析的每行數(shù)據(jù)插入到輸出列表中
    return out_list
def  save_csv(item,path): #數(shù)據(jù)存儲,將list數(shù)據(jù)寫入文件,防止亂碼
    with open(path, "a+", newline='',encoding="utf-8") as f: #創(chuàng)建utf8編碼文件
        csv_write = csv.writer(f) #創(chuàng)建寫入對象
        csv_write.writerows(item) #一次性寫入多行
if __name__=="__main__":
    for i in range(1,6):
        url="https://www.qidian.com/rank/fengyun?style=1&page={0}".format(i)
        html=get_html(url) #獲取網(wǎng)頁數(shù)據(jù)
        out_list=parser(html) #解析網(wǎng)頁,輸出列表數(shù)據(jù)
        save_csv(out_list,"d:\\book.csv") #數(shù)據(jù)存儲

存入數(shù)據(jù)庫

import pymysql
import requests
from lxml import etree
def get_html(url, time=3000):
    try:
        headers ={
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31"
        }
        r = requests.get(url, timeout=time,headers=headers)
        r.encoding = r.apparent_encoding
        r.raise_for_status()
        return r.text
    except Exception as err:
        print(err)
result = []
def parse_html(html):
    html = etree.HTML(html)
    for row in html.xpath('//*[@id="content"]/div/div[1]/ul/li'):
        Naame = row.xpath("div[2]/h2/a/text()")[0].strip()#//*[@id="content"]/div/div[1]/ul[1]/div[2]/h2/a
        score = row.xpath("div[2]/p[2]/span[2]/text()")[0].strip()#//*[@id="content"]/div/div[1]/ul[1]/div[2]/p[2]/span[2]
        price = row.xpath("div[2]/p[1]/text()")[0].strip().split("/")#//*[@id="content"]/div/div[1]/ul[1]/div[2]/p[1]/text()
        price= price[0]
        content= price[1]
        a=price[2]
        b= price[-1]
        detail = [Naame,score,price,content,a,b]
        result.append(detail)
def join_all(sql_insert,vals,**dbinfo):
    try:
        connet = pymysql.connect(**dbinfo)
        cursor = connet.cursor()
        cursor.executemany(sql_insert,vals)
        connet.commit()
        print('添加成功!')
    except Exception as err:
        print(err)
        connet.rollback()
    cursor.close()
if __name__=="__main__":
    for page in range(1,16):
        url="https://book.douban.com/latest?subcat=%E5%85%A8%E9%83%A8&p={0}".format(str(page))
        parms ={
            "host":"127.0.0.1",
            "port":3306,
            "user":"root",
            "passwd":"123456",
            "db":"db",
            "charset":"utf8"
        }
        html=get_html(url)
        parse_html(html)
    sql_insert = "INSERT INTO db(Naame,score,price,content,a,b)\
                           Values(%s,%s,%s,%s,%s,%s)"
    join_all(sql_insert,result,**parms)
    print(result)

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • Python實現(xiàn)隨機(jī)生成圖片驗證碼詳解

    Python實現(xiàn)隨機(jī)生成圖片驗證碼詳解

    這篇文章主要介紹了如何利用Python生成隨機(jī)的圖片驗證碼 并打印驗證碼的值,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起試試
    2022-01-01
  • Python中的迭代器你了解嗎

    Python中的迭代器你了解嗎

    迭代器是一種特殊的對象,它實現(xiàn)了迭代協(xié)議,允許按照一定的順序逐個訪問元素,本文就來帶大家深入了解一下Python中迭代器的使用,需要的可以參考下
    2023-05-05
  • python批量處理打開多個文件

    python批量處理打開多個文件

    這篇文章主要介紹了python批量處理打開多個文件,文章圍繞主題的相關(guān)內(nèi)容展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-06-06
  • 詳解python之多進(jìn)程和進(jìn)程池(Processing庫)

    詳解python之多進(jìn)程和進(jìn)程池(Processing庫)

    本篇文章主要介紹了詳解python之多進(jìn)程和進(jìn)程池(Processing庫),非常具有實用價值,需要的朋友可以參考下
    2017-06-06
  • python cs架構(gòu)實現(xiàn)簡單文件傳輸

    python cs架構(gòu)實現(xiàn)簡單文件傳輸

    這篇文章主要為大家詳細(xì)介紹了python cs架構(gòu)實現(xiàn)簡單文件傳輸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python學(xué)習(xí)教程之常用的內(nèi)置函數(shù)大全

    Python學(xué)習(xí)教程之常用的內(nèi)置函數(shù)大全

    python給我們提供了很多已經(jīng)定義好的函數(shù),下面這篇文章主要給大家介紹了關(guān)于Python學(xué)習(xí)教程之一些常用的內(nèi)置函數(shù),文中分享了關(guān)于數(shù)學(xué)函數(shù)、功能函數(shù)、類型轉(zhuǎn)換函數(shù)、字符串處理和序列處理函數(shù)的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07
  • python迭代器常見用法實例分析

    python迭代器常見用法實例分析

    這篇文章主要介紹了python迭代器常見用法,結(jié)合實例形式分析了Python迭代器概念、功能、常見操作方法及相關(guān)注意事項,需要的朋友可以參考下
    2019-11-11
  • 探索Python函數(shù)調(diào)用為何加速代碼執(zhí)行原理

    探索Python函數(shù)調(diào)用為何加速代碼執(zhí)行原理

    Python 作為一種解釋型語言,其執(zhí)行速度相對于編譯型語言可能會較慢,然而,在Python中,通常觀察到代碼在函數(shù)中運行得更快的現(xiàn)象,這個現(xiàn)象主要是由于函數(shù)調(diào)用的內(nèi)部優(yōu)化和解釋器的工作方式導(dǎo)致的,本文將深入探討這個現(xiàn)象,并通過詳細(xì)的示例代碼進(jìn)行解釋
    2024-01-01
  • 使用TensorFlow實現(xiàn)簡單線性回歸模型

    使用TensorFlow實現(xiàn)簡單線性回歸模型

    這篇文章主要為大家詳細(xì)介紹了使用TensorFlow實現(xiàn)簡單線性回歸模型,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • 使用Python在Excel中插入、修改、提取和刪除超鏈接

    使用Python在Excel中插入、修改、提取和刪除超鏈接

    超鏈接是Excel中的常用功能,通過點擊超鏈接可以快速跳轉(zhuǎn)到外部網(wǎng)站、本地文件或工作表中的特定單元格,有效提升數(shù)據(jù)訪問的效率和用戶體驗,這篇博客將詳細(xì)介紹如何使用Python在Excel中插入、修改、提取和刪除超鏈接,需要的朋友可以參考下
    2025-02-02

最新評論

木兰县| 廊坊市| 张掖市| 陵川县| 静乐县| 辽宁省| 潮州市| 呼图壁县| 北海市| 通道| 改则县| 阿城市| 沿河| 大安市| 安国市| 晋中市| 西和县| 独山县| 贵定县| 巧家县| 余姚市| 彝良县| 虎林市| 黄浦区| 桐庐县| 祁阳县| 泉州市| 城口县| 朝阳区| 延津县| 肥乡县| 兴国县| 扎囊县| 闽侯县| 佛冈县| 比如县| 伊宁县| 沧源| 梁平县| 裕民县| 革吉县|