You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup提取URL后,如何在文本文件中分隔各URL?

解决URL写入文件粘连问题的两种方法

方法1:写入时直接添加换行符

问题根源是你写入URL时没有添加分隔符,导致所有内容连在一起。只需修改写入语句,给每个URL加上换行符即可:

for a in soup.find_all('a', href=True):
    if "/xxxx/xxxxxxxx-" in a['href']:
        x = "https://www.unkown.com" + a['href']
        f.write(x + '\n')  # 追加换行符,让每个URL单独占一行
    else:
        pass

方法2:用列表存储后统一写入(修正你的数组用法)

你之前遇到数组第一个元素包含所有URL,应该是错误地用了字符串拼接而非逐个添加元素。正确的列表存储写法如下:

# 初始化空列表
url_list = []
for a in soup.find_all('a', href=True):
    if "/xxxx/xxxxxxxx-" in a['href']:
        x = "https://www.unkown.com" + a['href']
        url_list.append(x)  # 逐个将URL加入列表

# 统一写入文件,用换行符连接所有URL
with open('urls.txt', 'w') as f:
    f.write('\n'.join(url_list))

内容的提问来源于stack exchange,提问作者Daemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:50:01