python 爬蟲存入本地

2021-07-26 11:15:39 字數 1049 閱讀 4614

一,open函式

開啟本地檔案的方法

with

open('path','r') as f:

f.write('data')

path是檔案的路徑,r是read讀取,w就write寫入,f是操作這個連線的物件

二,操作字串的方法

替代用的format,乙個字串str裡面加上{}然後用.format(new_str)把new_str加入到{}裡

分片的split,乙個字串str後.split()在()裡是用什麼分片的字元,然後這個str被分成了幾段list,這樣就可以取出想要的字元。

三,寫入乙個文章

from bs4 import beautifulsoup

import requests

url = ''

resp = requests.get(url)

resp.encoding = 'utf-8'

soup = beautifulsoup(resp.text,'lxml')

title = soup.select('#t_486e105c010001s9')

pp = soup.select('#sina_keyword_ad_area2 > div > p > span > font')

for i in title:

title1 = i.get_text()

name = title1+'.txt'

with

open(name,'w',encoding='utf-8') as fo:

for i in pp:

fo.write(i.get_text())

文章的url是有規律的,只有最後的數字不同,可以用

str = ['{}'.format(n) for n in range(1,10)]
來批量處理。

題目可以用split()方法來處理。

python爬網頁存入本地檔案

自己寫的小 對齊上還需要改進 import requests import os from bs4 import beautifulsoup import bs4 defgethtmltext url try kv r requests.get url,headers kv r.raise for ...

python 爬蟲獲取json資料存入檔案時亂碼

解決python使用爬蟲獲取json格式的網頁,輸出以及寫入檔案亂碼的情況 import codecs resp requests.get url,headers headers result json.dumps resp.json ensure ascii false 若不指定ensure as...

Python爬蟲 將爬取的資料存入excle

本性專案從淘車網爬取資料並將爬下來的資料生成excle 安裝 lxml和xlsxwriter庫的時候飄紅,從terminal和python interpreter安裝都不行,最後試了試cmd 好像是先從cmd用清華映象裝,再從python interpreter裝,剛開始python interpr...