下载目标链接html到文本文件

2024-04-26 11:48:18 发布

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

我对python和Web爬行是完全陌生的。你知道吗

我正在尝试下载文本页中的单个目标链接。 到目前为止,我成功地提取了我需要的所有目标url,但不知道如何下载多个文件中的所有目标HTML文本。下面的代码只是在多个文件中显示同一篇文章。你知道吗

有人能帮帮我吗。你知道吗

url = ""
r  = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "lxml")
link1 = soup2.find_all('a', href=re.compile("drupal_lists"))

for t1 in link1:
    print(t1.attrs['href'])
link_data = requests.get(t.attrs['href']).text

import io
for i in link_data:
   link_data
   with io.open("file_" + str(i) + ".txt", 'w', encoding='utf-8') as f:
       f.write(str(i)+link_data)

Tags: 文件textin文本url目标fordata
1条回答
网友
1楼 · 发布于 2024-04-26 11:48:18

在代码的样式中,从事物发生变化时开始:

for i, t1 in enumerate(link1):  # Get indices and data in one go
   link_data = requests.get(t1.attrs['href']).text
   with io.open("file_" + str(i) + ".txt", 'w', encoding='utf-8') as f:
       f.write(link_data)  # no str(i) because that would mess with the HTML

相关问题 更多 >