requests爬蟲常用操作

# 安裝

pip install beautifulsoup4 #解析html用

pip install requests #請求用

# 使用

import requests

from bs4 import BeautifulSoup

--------------

# requests 用法

heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'

proxy = [

? {

? ? ? ? 'http': 'http://61.135.217.7:80',

? ? ? ? 'https': 'http://61.135.217.7:80',

? ? },{

? ? ? ? 'http': 'http://118.114.77.47:8080',

? ? ? ? 'https': 'http://118.114.77.47:8080',

? ? }

]

cookies = {'cookies_are':'working'}

例:

response = requests.get('http://www.baidu.com',headers=heads,params={'id':11},cookies=cookies,proxies=random.choice(proxy))

參數(shù)設(shè)置:

1. headers設(shè)置請求頭,params設(shè)置參數(shù),cookies設(shè)置,proxies設(shè)置代理

2. files上傳文件: files = {'file': open('report.xls', 'rb')}

3. timeout超時時間: timeout=0.001

4. allow_redirects是否重定向: allow_redirects=False

5. verify是否忽略證書用于https: requests.get('https://github.com', verify=False)

6. cert設(shè)置證書:requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))

7. 設(shè)置json數(shù)據(jù):json={'some': 'data'}

8. stream設(shè)置流用于大文件:

r = requests.get('https://api.github.com/events', stream=True)

chunk_size=100

with open(filename, 'wb') as fd:

? ? for chunk in r.iter_content(chunk_size):

? ? ? ? fd.write(chunk)

------

response = requests.post('http://www.baidu.com', data={'id':11})

response.status_code? # 得到狀態(tài)碼

response.url? ? ? ? ? # 得到請求url

response.headers? ? # 得到請求頭信息

response.cookies? ? # 得到cookie對象信息 response.cookies.get_dict() 得到字典形式

response.text? # 以文本形式顯示網(wǎng)頁源碼

response.content # 以字節(jié)流形式輸出用于保存文件或圖片

response.json() # 獲取json格式

response.encoding=response.apparent_encoding # encoding設(shè)置編碼,apparent_encoding獲取編碼

# Session 跨請求保持某些參數(shù)

s = requests.Session()

s.auth = ('user', 'pass')

s.headers.update({'x-test': 'true'})

s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

# both 'x-test' and 'x-test2' are sent

------------

from bs4 import Tag

BeautifulSoup 用法

soup=BeautifulSoup(response.text,"html.parser")

soup.prettify() #顯示得到數(shù)據(jù)

div=soup.find_all('div') #獲取所有標(biāo)簽

div[0].text #獲取文本

div=soup.select('#side') #獲取id為side的數(shù)據(jù) 支持大部分的CSS選擇器

tags=div.children #找到所有子級包括換行文本內(nèi)容

#過濾標(biāo)簽

for tag in tags:

? if type(tag)==Tag:

? ? print('%s 是標(biāo)簽'%tag)

img=soup.find('img',id='myimg') #獲取單個標(biāo)簽

img.name #獲取標(biāo)簽名

img.attrs #獲取字典

img.attrs.get('src') #獲取屬性值

# 獲取head 和body的兒子節(jié)點

contens = soup.head.contents

body_list = soup.body.contents

# 標(biāo)簽數(shù)的上行遍歷

.parent 節(jié)點的父親標(biāo)簽

.parents 節(jié)點先輩標(biāo)簽的迭代類型,用于循環(huán)遍歷先輩節(jié)點

soup.head.parent

soup.head.parents

# 標(biāo)簽數(shù)的平行遍歷 (條件 必須是一個父親節(jié)點下的)

.next_sibling 返回按照HTML文本順序的下一個平行節(jié)點標(biāo)簽

.previous_sibling 返回按照HTML文本順訊的上一個平行節(jié)點標(biāo)簽

.next_siblings: 迭代類型, 返回按照HTML順序的后續(xù)所有平行節(jié)點標(biāo)簽

.previous_siblings: 迭代類型, 返回按照HTML順序的前序所有平行節(jié)點標(biāo)簽

.find_all(re.compile("^b")) 通過正則表達式的 match() 來匹配內(nèi)容.例子中找出所有以b開頭的標(biāo)簽

.find_all("a", class_="sister") 按照CSS類名搜索

# find_all(name, attr, recursive, string, **kwargs) 搜索參數(shù)

返回一個類表類型,存儲查找的結(jié)果

name: 對標(biāo)簽名稱的檢索字符串

attrs: 對標(biāo)簽屬性值的檢索字符串, 可標(biāo)注屬性檢索

recursive: 是否對子孫全部檢索, 默認(rèn)為True

string:soup.find_all(string = 'Basic Python)

擴展方法:

1)<>.find(): 搜索且只返回一個結(jié)果,字符串類型,同.find_all()參數(shù)

2)<>.find_parents():在先輩節(jié)點中搜索,返回列表類型, 同find_all()參數(shù)

3)<>.find_parent(): 在先輩節(jié)點中返回一個結(jié)果, 字符串類型

4)<>.find_next_siblings():后續(xù)平行節(jié)點中搜索,返回列表類型

5)<>.find_next_sibling():后續(xù)平行節(jié)點返回一個結(jié)果,字符串類型

6)<>.find_previous_siblings(): 前序平行節(jié)點搜索,返回列表

7)<>.find_previous_sibling():前序平行節(jié)點返回一個結(jié)果,字符串類型

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容