【问题标题】:Why is requests.get() not working in a for loop?为什么 requests.get() 不能在 for 循环中工作?
【发布时间】:2019-07-03 01:43:31
【问题描述】:

我正在尝试抓取文本文件“tastyrecipes”中列出的网站列表,我目前有一个返回 url 的 for 循环,但不知道如何将 url 放入 requests.get () 不会出现 404 错误。网站单独返回 200 状态代码,查看 HTML 没有问题。

我已经尝试过字符串格式化,我做了

with open('tastyrecipes', 'r') as f:
    for i in f:
        source = requests.get("{0}".format(i)) 

但这并没有改变结果。

with open('tastyrecipes', 'r') as f:
    new_file = open("recipecorpus.txt", "a+")
    for i in f:
        source = requests.get(i)
        content = source.content
        soup = BeautifulSoup(content, 'lxml')
        list_object = soup.find('ol', class_='prep-steps list-unstyled xs-text-3')
        method = list_object.text
        new_file.write(method)
        new_file.close()

我预计 i 允许对文本文件中的 url 进行迭代抓取,但它返回 404 错误。

【问题讨论】:

  • 您能否修复缩进和引用,以及创建一个不需要某些我们不知道其内容的文件的Minimal, Complete, and Verifiable example 以帮助调试您的问题?另外,您是否尝试在请求之前放置一个调试语句,并在请求之前查看字符串设置为什么?
  • 我不确定我的缩进和引用有什么问题,我尝试在我的完整代码上方创建一个最小示例。我认为文件的内容并不重要,正如我所说,它只是一个 url 列表。我没有放调试语句,因为我必须查找如何做到这一点
  • 鉴于 HHTP 请求的性质,该站点很可能拒绝您的快速连接尝试或限制您的 IP 的速率。也许考虑在你的代码中添加一些time.sleeps,看看性能是否有所提高
  • @JonathanDyke 我看到您修复了缩进,并且引用我的意思是 ('tastyrecipes', 'r'') 行包含一个额外的引用。此外,如果您不告诉我们或向我们展示,我们也不可能知道文件中的内容或格式。
  • 如果一个 URL 返回 200,另一个返回 404,则这两个 URL 不同。

标签: python


【解决方案1】:

文件f 中的行i 以尾随换行符返回,这些换行符不属于正常的URL。在将i 传递给requests.get() 之前,您需要使用i = i.rstrip('\r\n') 删除换行符。

【讨论】:

  • 如果是这个问题,他也可以"""{}""".format(url)我相信。
  • @IMCoins:和url一样,只是多了一些步骤。
  • 等待tastyrecipessn-p
【解决方案2】:

分析

我不可能找到 requests.get 本身的问题。

import requests
recipes=['https://tasty.co/recipe/deep-fried-ice-cream-dogs',
        'https://tasty.co/recipe/fried-shrimp-and-mango-salsa-hand-rolls',
         'https://tasty.co/recipe/brigadeiros']
print(list(map(requests.get, recipes)))
[<Response [200]>, <Response [200]>, <Response [200]>]

for recipe in recipes: print(requests.get(recipe))
<Response [200]>
<Response [200]>
<Response [200]>

可能的问题

1。 404本身不是问题

如果有不正确的网址,这是一个合法的答案。

2。 tastyrecipes-file 中的尾随 \n 和空格

那是@jwodder 的suggested

【讨论】:

  • 是的,是文件中的尾随空格导致错误,我查看了终端中文本文件的内容,它似乎工作正常
【解决方案3】:

首先检查url是否有效 from urlparse import urlsplit def is_valid_url(url=''): url_parts = urlsplit(url) return url_parts.scheme and url_parts.netloc and surl_partsp.path

with open('tastyrecipes', 'r') as f: new_file = open("recipecorpus.txt", "a+") for i in f: if is_valid_url(i) source = requests.get(i) content = source.content soup = BeautifulSoup(content, 'lxml') list_object = soup.find('ol', class_='prep-steps list-unstyled xs-text-3') method = list_object.text new_file.write(method) new_file.close()

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多