[英]Python - How to loop through a text file of urls and pass all the urls into a redirect handler
[英]How to make Python go through URLs in a text file, check their status codes, and exclude all ones with 404 error?
我尝试了以下脚本,但不幸的是 output 文件与输入文件相同。 我不确定它有什么问题。
import requests
url_lines = open('banana1.txt').read().splitlines()
remove_from_urls = []
for url in url_lines:
remove_url = requests.get(url)
print(remove_url.status_code)
if remove_url.status_code == 404:
remove_from_urls.append(url)
continue
url_lines = [url for url in url_lines if url not in remove_from_urls]
print(url_lines)
# Save urls example
with open('banana2.txt', 'w+') as file:
for item in url_lines:
file.write(item + '\n')
您的代码似乎没有错误,但很少有东西可以帮助使其更具可读性和一致性。 第一个行动方案应该是确保至少有一个 url 会返回 404 状态代码。
请确保正确关闭文件。 此外, file
object 是一个行迭代器,您可以很容易地将其转换为列表。 使代码更具可读性的另一个技巧是使用 Python set
。 所以你可以像这样阅读文件:
with open("banana1.txt") as fid:
url_lines = set(fid)
然后,您只需删除所有不起作用的链接:
not_working = set()
for url in url_lines:
if requests.get(url).status_code == 404:
not_working.add(url)
working = url_lines - not_working
with open("banana2.txt", "w") as fid:
fid.write("\n".join(working))
此外,如果某些链接指向同一服务器,则应使用requests.Session
class:
from requests import Session
session = Session()
然后用session.get
替换requests.get
,你应该得到一些性能提升,因为 Session 使用保持活动连接和许多其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.