【发布时间】:2018-10-15 15:00:02
【问题描述】:
我在 python 中编写了一个脚本来抓取通过代理生成的请求的 url。我在脚本中使用了shuffle() 来随机获取代理。该脚本在某种程度上做得很好。此脚本的问题是当它无法使用任何有效的代理时,由于循环,它会转到另一个 url。如何以这种方式纠正我的脚本,以便它会尝试使用列表中的每个代理(如果需要)来获取所有 urls。
这是我的尝试:
import requests
from random import shuffle
url = "https://stackoverflow.com/questions?page={}&sort=newest"
def get_random_proxies():
proxies = ['35.199.8.64:80', '50.224.173.189:8080', '173.164.26.117:3128']
shuffle(proxies)
return iter(proxies)
for link in [url.format(page) for page in range(1,6)]:
proxy = next(get_random_proxies())
try:
response = requests.get(link,proxies={"http": "http://{}".format(proxy) , "https": "http://{}".format(proxy)})
print(f'{response.url}\n{proxy}\n')
except Exception:
print("something went wrong!!" + "\n")
proxy = next(get_random_proxies_iter())
我的输出:
https://stackoverflow.com/questions?page=1&sort=newest
35.199.8.64:80
https://stackoverflow.com/questions?page=2&sort=newest
50.224.173.189:8080
something went wrong!!
https://stackoverflow.com/questions?page=4&sort=newest
50.224.173.189:8080
something went wrong!!
您可以看到'page=3&sort=newest' 和'page=5&sort=newest' 这两个网址没有响应,而我的两个代理仍在工作。
后记:它们是免费代理,所以我特意发布了它们。
【问题讨论】:
标签: python python-3.x web-scraping proxy python-requests