为什么是请求.get()没有在for循环中工作?

2024-09-28 01:33:41 发布

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

我正在尝试抓取一个在文本文件“tastyrecipes”中列出的网站列表,我目前有一个for循环,它返回url,但无法确定如何将url放入请求.get()而没有收到404错误。网站分别返回200个状态码,浏览HTML没有问题。在

我尝试过字符串格式,我做过

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

然而,这并没有改变结果。在

^{pr2}$

我希望我允许迭代地抓取文本文件中的url,但是它返回404错误。在


Tags: 字符串url列表forget网站状态html
3条回答

文件f中的i将返回尾随的新行,这些新行不属于普通的url。在将i传递给requests.get()之前,需要删除带有i = i.rstrip('\r\n')的换行符。在

首次检查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()

分析

我不可能发现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-文件中的尾随\n和空格

这是@jwodder的suggested

相关问题 更多 >

    热门问题