python3 urllib爬蟲抓取記錄

2021-08-11 12:19:56 字數 2387 閱讀 8596

import re

import os

from urllib import request

#抓取整個頁面下來

data=request.urlopen('').read().decode()

#正則提取所有文章標題,

ruler = re.compile('(.*?)',re.s)

match = ruler.findall(data)

#把抓取到的資料遍歷

for x in match:

#把 \r\n 和空格 都去掉

content = x.replace('\r\n','').replace(' ','')

#檔案儲存路徑,如果沒有,則建立

path = 'csdn'

if not os.path.exists(path):

os.makedirs(path)

#儲存檔名

file_path = path+'/csdn.txt'

#開啟檔案

f = open(file_path,'a+')

#寫入檔案

f.write(content)

#關閉檔案

f.close()

pass

#模擬瀏覽器傳送get請求,通過往request物件新增http頭,偽裝成瀏覽器

from urllib import request

req = request.request('')

data = request.urlopen(req).read().decode()

print(data)

# 目的:模擬登入 csdn

print("嘗試解壓縮...")

data = gzip.decompress(data)

print("解壓完畢")

except:

print("未經壓縮,無需解壓")

return data

def getlt(data):

cer = re.compile('name=\"lt\" value=\"(.*)\"')

strlist = cer.findall(data)

return strlist[0]

def getexecution(data):

cer = re.compile('name=\"execution\" value=\"(.*)\"')

strlist = cer.findall(data)

return strlist[0]

def getopener(head):

# cookies 處理

# header資訊可以通過firebug獲得

header =

url = url = ''

opener = getopener(header)

op = opener.open(url)

data = op.read()

data = ungzip(data)

lt = getlt(data.decode())

execution = getexecution(data.decode())

username = "帳號"

password = "密碼"

postdict =

postdata = urllib.parse.urlencode(postdict).encode()

op = opener.open(url,postdata)

data = op.read()

data = ungzip(data)

print(data.decode())

Python3 urllib庫爬蟲 基礎

add header 新增報頭url req urllib.request.request url req.add header user agent mozilla 5.0 x11 ubuntu linux x86 64 rv 56.0 gecko 20100101 firefox 56.0 da...

python3 urllib使用debug輸出

python2.7.5中使用debug輸出,可以採用如下方式 python3 中統一使用的是urllib模組庫,將python2中的urllib和urllib2進行了整合,試圖按上述方式編寫 如下 python3.4.2 window7 cmd 沒有語法錯誤提示,但是,也沒有任何除錯資訊出來。還有另...

Python3 urllib抓取指定URL的內容

python爬蟲主要使用的是urllib模組,python2.x版本是urllib2,很多部落格裡面的示例都是使用urllib2的,因為我使用的是python3.3.2,所以在文件裡面沒有urllib2這個模組,import的時候會報錯,找不到該模組,應該是已經將他們整合在一起了。下面是乙個簡單的 ...