在使用Python的requests库进行爬虫时,可以通过以下方法来提高稳定性:
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
url = "https://example.com"
response = requests.get(url, headers=headers)
import requests
proxies = {
"http": "http://your_proxy_ip:port",
"https": "https://your_proxy_ip:port"
}
url = "https://example.com"
response = requests.get(url, proxies=proxies)
import time
import requests
url = "https://example.com"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
for _ in range(10): # 爬取10次
response = requests.get(url, headers=headers)
time.sleep(1) # 每次请求之间间隔1秒
import requests
from requests.exceptions import RequestException
url = "https://example.com"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 如果响应状态码不是200,抛出异常
except RequestException as e:
print(f"请求出错: {e}")
import requests
from concurrent.futures import ThreadPoolExecutor
url = "https://example.com"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
def fetch(url):
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.text
except RequestException as e:
print(f"请求出错: {e}")
return None
urls = [url] * 10 # 假设有10个相同的URL需要爬取
with ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(fetch, urls))
通过以上方法,可以提高Python requests爬虫的稳定性。