在Python爬虫中设置headers通常是为了模拟浏览器访问,避免被网站识别为爬虫并拒绝服务。以下是设置headers的基本步骤和示例代码:
使用`requests`库设置headers:
import requests
url = 'http://www.example.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Referer': 'http://www.baidu.com/'
}
response = requests.get(url, headers=headers)
print(response.text)
使用`urllib`库设置headers:
import urllib.request
import urllib.parse
url = 'http://www.example.com'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'username': 'cqc',
'password': 'XXXX'
}
headers = {
'User-Agent': user_agent
}
data = urllib.parse.urlencode(values).encode('utf-8')
request = urllib.request.Request(url, data=data, headers=headers)
response = urllib.request.urlopen(request)
page = response.read()
print(page.decode('utf-8'))
使用`Selenium`设置headers:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('lang=zh_CN')
driver = webdriver.Chrome(options=options)
driver.get('http://www.example.com')
请注意,当使用`requests`库时,你可以使用`requests.Session`来保持cookies和重定向,这样可以更加自然地与网站交互。
还需要注意,网站可能会有反爬机制,可能需要额外的headers,如`Referer`,或者使用代理IP来避免被封禁。