爬蟲學習記錄

2021-10-09 01:16:29 字數 3664 閱讀 1023

如何將字串轉換為字典:

# 字典推導式

cookies=

"anonymid=j3jxk555-nrn0wh; _r01_=1; _ga=ga1.2.1274811859.1497951251; _de=bf09ee3a28ded52e6b65f6a4705d973f1383380866d39ff5; [email protected]; depovince=bj; jebecookies=54f5d0fd-9299-4bb4-801c-eefa4fd3012b|||||; jsessionid=abci6tfwh4n4t_awjnvdw; ick_login=4be198ce-1f9c-4eab-971d-48abfda70a50; p=0cbee3304bce1ede82a56e901916d0949; first_login_flag=1; ln_hurl= t=79bdd322e760beae79c0b511b8c92a6b9; societyguester=79bdd322e760beae79c0b511b8c92a6b9; id=327550029; xnsid=2ac9a5d8; loginfrom=syshome; ch_id=10016; wp_fold=0"

cookies =

#字典是無序的

# 列表推導式

self.url_temp =

""+ tieba_name +

"&ie=utf-8&pn={}"

return

[self.url_temp.

format

(i *50)

for i in

range

(1000

)]

requests用法:

tips:response.text 物件中,名詞一般是屬性,動詞一般是方法,需要加括號

byte型資料(字串前面加b'的),解碼時用decode:

例:b'\.... \r\n'

response.content.decode(

)# requests中解決編譯碼的方法

response.content.decode(

)response.content.decode(

"gbk"

)response.text

import json

json.loads(response.content.decode(

))

json.loads()和json.dump()

html_str = parse_url(url)

# json.loads把json字串轉化為python型別(字典)

ret1 = json.loads(html_str)

# json.dumps能夠把python型別轉化為json字串

# ensure_ascii=false設定編碼, indent=4設定換行縮排,都是為了使資料看起來更美觀

# encoding="utf-8" 也是必要的

with

open

("douban.json"

,"w"

,encoding=

"utf-8"

)as f:

f.write(json.dumps(ret1, ensure_ascii=

false

, indent=4)

)

常用正規表示式的方法:

re.compile(編譯)

pattern.match(從頭找乙個)

pattern.search(找乙個)

pattern.findall(找所有)

pattern.sub(替換)

使用注意點:

獲取屬性@符號//

示例:

//ul[@id

="detail-list"

]/li/a[@class

='image share-url'

]/@href

# /@href 用於獲取標籤中的網頁鏈結

需要用到lxml庫

from lxml import etree

text =

'''

'''html = etree.html(text)

print

(html)

#檢視element物件中包含的字串

print

(etree.tostring(html)

.decode())

#獲取class為item-1 li下的a的herf

ret1 = html.xpath(

"//li[@class='item-1']/a/@href"

)#獲取class為item-1 li下的a的文字

ret2 = html.xpath(

"//li[@class='item-1']/a/text()"

)#分組,根據li標籤進行分組,對每一組繼續寫xpath

建立乙個scrapy專案

scrapy startproject [專案名]
生成乙個爬蟲

# 需要先進入專案檔案下

cd myproject

scrapy genspider [爬蟲名]

[網域名稱]

# 執行爬蟲

scrapy scrawl itcast

提取資料

完善spider,使用xpath等方法

儲存資料

pipeline中儲存資料

爬蟲學習記錄 01

在檔案儲存及資料型別中的一些小問題 結語python 3.6 使用原生自帶的 urllib 模組進行爬蟲的開始 匯入模組urllib的request框架 import urllib.request 使用urlopen方法模擬使用者開啟網頁,以www.baidu.com為例。import urllib...

python爬蟲入門學習記錄

在使用爬蟲前確保requests和beautifulsoup4模組都已經安裝好了 pip install requests pip install beautifulsoup4 beautifulsoup4使用手冊 簡單的示列 import requests 匯入requests包 url strh...

爬蟲 基本請求 學習記錄

學習筆記 1.引數直接放在url import requests response requests.get url name gemey 男 並列 print response.text 2.引數放在data裡面,發起請求時params請求引數指定data import requests data...