簡體   English   中英

為列表中的每個項目添加換行符,使用 beautifulsoup 找到項目

[英]Add line break for each item in list,items were found by using beautifulsoup

我正在嘗試查找網站中的所有照片鏈接,為此我使用 BeautifulSoup。 這是我的代碼:

import requests
from bs4 import BeautifulSoup as bs

url = "http://cupp.cyberport.hk/zh_TW/front_programmes/index"
webpage = requests.get(url)
soup = bs(webpage.content, "html.parser")
images = []
for img in soup.findAll('img'):
   images.append(img.get('src'))
   with open("photo_links.txt", "w") as text_file:
      text_file.write(str(images))

結果是

['https://www.cyberport.hk/images/logo.jpg','https://www.cyberport.hk/img/weather_icon/black/54.png','https://www.cyberport.hk/images/facebook.jpg', 'https://www.cyberport.hk/images/twitter.jpg','https://www.cyberport.hk/images/linkin.jpg', 'http://cupp.cyberport.hk/files/general_content/upload/12/hkcityu_logo.jpg','http://cupp.cyberport.hk/files/general_content/upload/13/hkbu_logo.jpg'] 

列表中的所有項目都打印在 txt 文件中的一行中。

我希望每個項目都用“\n”分隔

像這樣

['https://www.cyberport.hk/images/logo.jpg',
'https://www.cyberport.hk/img/weather_icon/black/54.png',
'https://www.cyberport.hk/images/facebook.jpg', 
'https://www.cyberport.hk/images/twitter.jpg',
'https://www.cyberport.hk/images/linkin.jpg', 
'http://cupp.cyberport.hk/files/general_content/upload/12/hkcityu_logo.jpg',
'http://cupp.cyberport.hk/files/general_content/upload/13/hkbu_logo.jpg'] 

如何修改代碼以獲得我喜歡的結果?

謝謝你。

您可以嘗試以下解決方案嗎?

修改以下代碼

text_file.write(str(images))

到下面的代碼

text_file.write(str(images)+'\n')

你可以這樣做:

import requests
from bs4 import BeautifulSoup as bs

url = "http://cupp.cyberport.hk/zh_TW/front_programmes/index"
webpage = requests.get(url)
soup = bs(webpage.content, "html.parser")
images = []
for img in soup.findAll('img'):
   images.append(img.get('src'))

url_list = '",\n"'.join(images)
with open("../test_files/photo_links.txt", "w") as text_file:
   text_file.write(f'"{url_list}",')

'\n'.join(images)創建由\n連接的images中的項目字符串。

您可以使用字符串格式來實現它。 只需在兩個方括號之間注入帶有',\n'串聯列表元素:

text_file.write(f"[{',\n'.join(images)}]")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM