requests庫
安裝:
$ pip3 install requests
基本使用:
代碼:
import requests
url = 'http://www.httpbin.org/' # 請求路徑
data = {'a': 'aa', 'b': 'bb'} # 請求參數(shù)
# get請求
response = requests.get(url + 'get', data)
print(response.text) # 輸出請求返回的內(nèi)容
# post請求
response = requests.post(url + 'post', data)
print(response.json()) # 輸出請求返回的內(nèi)容并轉(zhuǎn)換為JSON
控制臺:

配合正則表達式(爬取圖片并保存):
代碼:
import os
import shutil
import re
import requests
abspath = os.path.abspath('.') # 本地絕對路徑
keyword = '城市攝影' # 搜索關鍵字
url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1594807659507_R&pv=&ic=&nc=1&z=&hd=&latest=©right=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=' + keyword
# 下載圖片
# downloadUrl[String]: 下載路徑
# savePath[String]: 保存路徑
def downloadImg(downloadUrl, savePath):
print('開始下載', downloadUrl)
response = requests.get(downloadUrl, stream=True) # 下載
if response.status_code == 200: # 下載成功
with open(savePath, 'wb') as f: # 打開文件
response.raw.deconde_content = True
shutil.copyfileobj(response.raw, f) # 寫入文件
# 爬取圖片信息
# url[String]:爬取地址
def craw(url):
# 請求頭部信息
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
response = requests.get(url, headers=headers) # 請求url
# 正則表達式
pattern = re.compile(
r'{"thumbURL":"(.*?)".*?"middleURL":"(.*?)".*?"largeTnImageUrl":"(.*?)".*?"fromURL":"(.*?)".*?"fromPageTitle":"(.*?)".*?}',
re.S)
result = re.findall(pattern, response.text) # 根據(jù)正則表達式獲取圖片信息
for x in result:
thumbURL, middleURL, largeTnImageUrl, fromURL, fromPageTitle = x
downloadUrl = ''
if largeTnImageUrl != '': # 高質(zhì)量圖片路徑
downloadUrl = largeTnImageUrl
elif middleURL != '': # 中等質(zhì)量圖片路徑
downloadUrl = middleURL
elif thumbURL != '': # 縮略圖路徑
downloadUrl = thumbURL
# 設置圖片標題
title = re.sub(r'<.*?>|\\|\/|\.$', '', fromPageTitle) # 清除斜線/html標簽/結(jié)尾的.
# 獲取圖片擴展名
ext = re.search(r'.[a-z]*$', downloadUrl).group(0)
# 拼接保存路徑
savePath = os.path.join(abspath, 'files', title + ext)
# 下載
downloadImg(downloadUrl, savePath)
# 開始爬取圖片
craw(url)
控制臺:

下載的文件:

BeatifulSoup庫
安裝:
# 安裝BeatifulSoup庫
pip3 install bs4
# 安裝lxml解析包
pip3 install lxml
基本使用:
from bs4 import BeautifulSoup
import requests
response = requests.get(url) # 請求url
soup = BeautifulSoup(response.text, 'lxml') # 解析請求返回的內(nèi)容
soup.title # 獲取title標簽
soup.title.string # 獲取title標簽的內(nèi)容
soup.p['class'] # 獲取p標簽的class屬性值
soup.find(id="link1") # 獲取id為link1的標簽
soup.find_all('a') # 獲取所有a標簽
soup.find('table', {'data-name': 'userList'} # 獲取屬性data-name為userList的table標簽
for link in soup.find_all('a'): # 遍歷所有a標簽
print(link.get('href')) # 輸出a標簽的href屬性
爬取新聞:
代碼:
from bs4 import BeautifulSoup
import requests
page = 1 # 頁碼
url = 'http://www.cncga.org/news.asp?page='+ str(page) +'&types=3' # 請求地址
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
response = requests.get(url, headers=headers) # 請求url
response.encoding = 'gb2312' # 設置編碼
soup = BeautifulSoup(response.text, 'lxml') # 解析返回內(nèi)容
soup_table = soup.find('table', {'width': '760'}) # 找到新聞列表的容器
for a in soup_table.find_all('a', {'class': 'a2'}): # 獲取所有的a標簽并遍歷
print(a.string, a.get('href')) # 輸出標題和鏈接地址
控制臺:
