User-Agent反爬蟲
import requests
from bs4 import BeautifulSoup
url = 'http://www.porters.vip/verify/uas/index.html#'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
'''
使用BeautifulSoup爬取本週熱點內容
'''
for data in soup.find_all('li', {'class': 'list-group-item'}):
print(data.string)
'''
User-Agent就是請求字段之一,服務器能夠從User-Agent對應的值中識別客戶端使用的操作系統、
CPU類型、瀏覽器、瀏覽器引擎、操作系統語言等。
瀏覽器User-Agent字段值的格式爲:
瀏覽器標識 (操作系統標識;加密等級標識;瀏覽器語言) 渲染引擎標識 版本信息
服務器端選擇User-Agent作爲校驗對象,是因爲很多編程語言和軟件有默認的標識。
在發起網絡請求的時候,這個標識會作爲請求頭參數中的User-Agent字段值被髮送到服務器。
如果使用Python中Requests庫向服務器發起HTTP請求時,服務器讀取的User-Agent值爲:
python-requests/2.21.0
很顯然,當訪問次數過多時,服務器識別出來爬蟲,會將此User-Agent拉入黑名單
所以,實際爬蟲時,可以建立一個User-Agent池,使用時隨機抽取
常見的用於反爬蟲的頭域還有 Host 和 Referer
當爬蟲請求時經常失敗,就要考慮是不是User-Agent反爬蟲手段了
'''
Cookie反爬蟲
import requests
from bs4 import BeautifulSoup
'''
目標爬取 公告標題
直接請求,響應碼:200,請求成功
'''
url = 'http://www.porters.vip/verify/cookie/content.html'
headers = {
'Cookie': 'isfirst=789kq7uc1pp4c'
}
response = requests.get(url, headers=headers)
print(response.status_code)
soup = BeautifulSoup(response.text, 'lxml')
print(soup.find('h1').text)
print(response.text)
'''
返回的不是我們目標頁面的公告標題,查看response.text響應正文,發現並不是我們的目標網頁
並且嘗試在Firefox瀏覽器開發者工具中network欄中發現,content.html文件的響應碼爲302
響應碼302表示重定向,所以,網站的開發人員,希望用戶從統一的入口進入,
對直接訪問公告內容頁的請求進行重定向。
'''
print(soup.find('h1').text)