我正在尝试抓取一个在文本文件“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:
文件
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
本身的问题。在可能出现的问题
1。404本身不是问题
如果有不正确的网址,这是一个合理的答案。在
2。
tastyrecipes
-文件中的尾随\n和空格这是@jwodder的suggested
相关问题 更多 >
编程相关推荐