在循环中使用请求提供的HTML与在循环外使用不同

2024-04-26 23:06:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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内容。生成的URL是工作的,我得到了一个200 status\u代码,但是当第二个循环尝试使用表时返回了一个NoneType对象,这表明它从来没有得到我最初想要的HTML(但是如果我在循环外运行它,我确实得到了它)。你知道吗

对于那些提问的人来说,下面是日期是如何生成的。你知道吗

   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)]

Tags: inhttpsurlfordatetimedatetimehtml
3条回答

为了这个答案,让我们假设d的值等于2018-07-07 00:00:00。你知道吗

尽管如此,当你跑步时:

date = str(d).replace("00:00:00", "")

您忘记了2018-07-0700:00:00之间的空格。你知道吗

所以您应该将这行替换为:

date = str(d).replace(" 00:00:00", "")

希望这能解决你的问题:)

网站将限制请求的数量。为了解决这个问题,您需要指定请求头。试试这个:

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)

您可能会使网站过载,一次发送的请求太多,并且超时。按照@hootnot的建议,尝试在循环中放置一个time.sleep(1)。如果(1)不够,请尝试更长的超时时间。你知道吗

相关问题 更多 >