我正在尝试使用Python从一个网站上获取历史汇率。如果我手动抓取站点:
url = "https://www.x-rates.com/historical/?from=USD&amount=1&date=2018-07-12"
page = requests.get(url, timeout=5)
soup = BeautifulSoup(page.content, "html.parser")
table = soup.find("tbody")
结果就是我正在寻找的正确的HTML。
但是,如果我在这个循环中使用相同的块:
for d in date_generated:
date = str(d).replace("00:00:00", "")
url = "https://www.x-rates.com/historical/?from=USD&amount=1&date=" + date
page = requests.get(url, timeout=5)
soup = BeautifulSoup(page.content, "html.parser")
table = soup.find("tbody")
for i,x in zip(table.find_all("a"), table.find_all("td", class_="")):
time.sleep(3)
request += 1
elapsed_time = time.time() - start_time
print(i.text.strip(), x.text.strip())
我得不到正确的HTML内容。我得到了一个200HTML值,但在第二个循环中,当它试图使用表时,返回了一个NoneType对象,这表明它从一开始就没有得到我想要的status_code (但如果我在循环之外运行它,我就得到了它)。
对于那些有疑问的人,这里是如何生成日期的。
start_time = time.time()
start = datetime.datetime.strptime("2018-07-07", "%Y-%m-%d")
end = datetime.datetime.strptime("2018-07-12", "%Y-%m-%d")
date_generated = [start + datetime.timedelta(days=p) for p in range(0, (end-
start).days)]
发布于 2018-07-13 07:25:56
网站将限制请求的数量。为了解决这个问题,您需要指定请求头部。试试这个:
for d in date_generated:
date = str(d).replace("00:00:00", "")
url = "https://www.x-rates.com/historical/?from=USD&amount=1&date=" + date
head = {'user-agent': ('Mozilla/5.0 (X11; Linux x86_64)'
'AppleWebKit/537.36 (KHTML, like Gecko)'
'Chrome/66.0.3359.139 Safari/537.36'),
'referer': None}
head['referer'] = url
page = requests.get(url, timeout=5, headers=head)
发布于 2018-07-13 07:18:19
你可能会使网站超载,一次发送过多的请求,并被置于超时状态。按照@hootnot的建议,尝试在循环中放置一个time.sleep(1)
。如果(1)还不够,请尝试更长的超时。
https://stackoverflow.com/questions/51315550
复制相似问题