如何在Scrapy中設定輪換代理
Scrapy內建的HttpProxyMiddleware從request.meta讀取代理設定。使用輪換閘道時,您只需設定一個URL,每個請求仍會獲得新IP。
步驟
- 保持HttpProxyMiddleware啟用(預設即啟用)
- 在每個請求的meta={"proxy": url}中設定,或在start_requests中設定
- 將使用者名稱和密碼放入 proxy URL 中
- 如果網站仍然進行速率限制,請降低 CONCURRENT_REQUESTS_PER_DOMAIN
範例程式碼
import scrapy
PROXY = "http://USERNAME-cc-gb:PASSWORD@gw.gbproxies.cc:10000"
class PricesSpider(scrapy.Spider):
name = "prices"
start_urls = ["https://example.com/catalog"]
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url, meta={"proxy": PROXY})
def parse(self, response):
for href in response.css("a.product::attr(href)").getall():
yield response.follow(href, self.parse_item, meta={"proxy": PROXY})
def parse_item(self, response):
yield {"title": response.css("h1::text").get(), "url": response.url}將USERNAME和PASSWORD替換為控制台Proxies頁面中的代理登入資訊。端口10000是住宅HTTP代理;各產品端口請見下方。
提示
- 關閉 IMAGES_ENABLED 並避免媒體下載以節省 GB
- 使用 DOWNLOAD_TIMEOUT 30 和 RETRY_TIMES 3 以確保穩定運行
常見問題
我需要使用輪換中介軟體嗎?
不需要。閘道會自動輪換;一個 proxy URL 就足夠了。