4 回答

TA贡献1834条经验 获得超8个赞
这是实现其他人暗示的快速方法:
import requests
from bs4 import BeautifulSoup
with open('input.txt', 'r') as f_in:
for i, line in enumerate(map(str.strip, f_in)):
if not line:
continue
...
with open(f'output_{i}.txt', 'w') as f:
f.write(data + "\n")
print(data)

TA贡献1898条经验 获得超8个赞
您可以使用open('something.txt', 'w')
. 如果找到该文件,它将删除其内容。否则,它会创建一个名为“something.txt”的新文件。现在,您可以使用它file.write()
来写您的信息了!

TA贡献1780条经验 获得超1个赞
我不确定,如果我理解你的问题是正确的。
我会创建一个数组/列表,并为每个 url 请求和响应创建一个对象。然后将对象添加到数组/列表并为每个对象写入一个不同的文件。

TA贡献1784条经验 获得超7个赞
至少有两种方法可以为每个 url 生成文件。一个,如下所示,是创建文件的一些数据唯一数据的散列。在这种情况下,我选择了类别,但您也可以使用文件的全部内容。这将创建一个用于文件名的唯一字符串,这样具有相同类别文本的两个链接在保存时不会相互覆盖。
另一种方法(未显示)是在数据本身中找到一些唯一值,并将其用作文件名而不对其进行哈希处理。然而,这可能会导致比它解决的问题更多的问题,因为 Internet 上的数据不应该被信任。
这是您的代码,其中包含用于文件名的 MD5 哈希。MD5 不是密码的安全散列函数,但它可以安全地创建唯一的文件名。
更新的片段
import hashlib
import requests
from bs4 import BeautifulSoup
with open('input.txt', 'r') as f_in:
for line in map(str.strip, f_in):
if not line:
continue
response = requests.get(line)
data = response.text
soup = BeautifulSoup(data, 'html.parser')
categories = soup.find_all("a", {"class":'navlabellink nvoffset nnormal'})
for category in categories:
data = line + "," + category.text
filename = hashlib.sha256()
filename.update(category.text.encode('utf-8'))
with open('{}.html'.format(filename.hexdigest()), 'w') as f:
f.write(data + "\n")
print(data)
添加代码
filename = hashlib.sha256()
filename.update(category.text.encode('utf-8'))
with open('{}.html'.format(filename.hexdigest()), 'w') as f:
捕获更新的页面
如果您关心在不同时间点捕获页面内容,请散列文件的全部内容。这样,如果页面中的任何内容发生更改,页面之前的内容都不会丢失。在这种情况下,我对 url 和文件内容进行哈希处理,并将哈希值与 URL 哈希值和文件内容的哈希值连接起来。这样,当目录排序时,文件的所有版本都是可见的。
hashed_contents = hashlib.sha256()
hashed_contents.update(category['href'].encode('utf-8'))
with open('{}.html'.format(filename.hexdigest()), 'w') as f:
for category in categories:
data = line + "," + category.text
hashed_url = hashlib.sha256()
hashed_url.update(category['href'].encode('utf-8'))
page = requests.get(category['href'])
hashed_content = hashlib.sha256()
hashed_content.update(page.text.encode('utf-8')
filename = '{}_{}.html'.format(hashed_url.hexdigest(), hashed_content.hexdigest())
with open('{}.html'.format(filename.hexdigest()), 'w') as f:
f.write(data + "\n")
print(data)
添加回答
举报