python - Python读取嵌入代码,提取url并将url标题写入新的csv文件
问题描述
所以我在这个 csv 文件中有多个嵌入代码,我想读取这些 url 并将它们的标题标签复制到一个新的 csv 中。
我能够做到,但是格式有点出乎意料。
from bs4 import BeautifulSoup
import requests
import csv
with open('test.csv','r') as f:
csv_raw = f.read()
with open('newtest.csv','w') as ff:
cw = csv.writer(ff)
split_csv=csv_raw.split('\n')
#split_csv.remove('')
separator=","
for each in split_csv:
url_row_index=0
url = each.split(separator)[url_row_index]
url_delete = '<iframe width="560" height="315" src="' #delete extra texts
url_delete2 = '" frameborder="0" allowfullscreen></iframe>' #delete extra texts
url2 = url.replace(url_delete,'')
url3 = url2.replace(url_delete2,'')
html=requests.get(url3).content
soup=BeautifulSoup(html,'html.parser')
namelist = soup.title.string
word_delete = 'Video ' #delete extra wordings - Video
word_delete2 = '.mp4 (cloned)' #delete extra wordings - .mp4 (cloned)
namelist2 = namelist.replace(word_delete,'')
namelist3 = namelist2.replace(word_delete2,'')
print(namelist3)
cw.writerow(namelist3)
#So say in the original csv file, these are the embed codes
<iframe width="560" height="315" src="https://www.fembed.com/v/2222222" frameborder="0" allowfullscreen></iframe>
<iframe width="560" height="315" src="https://www.fembed.com/v/1111111" frameborder="0" allowfullscreen></iframe>
标题标签是
视频 111helloworld111.mp4(克隆)
视频 222helloworld222.mp4(克隆)
运行代码后,我将能够打印出这些
111你好世界111
222你好世界222
我希望在新的 csv 文件中看到它们
但是,在新的 csv 文件中,它会是这样的
1,1,1,h,e,l,l,o,w,o,r,l,d,1,1,1
2,2,2,h,e,l,l,o,w,o,r,l,d,2,2,2
我的代码有问题,但我只是不知道它是什么。
任何帮助,将不胜感激
解决方案
排序。感谢@njzk2。这真的是我对python的误解。在这种情况下,我应该将 namelist3 的输出视为列表,而不是字符串,正如@njzk2 在他的回复中指出的那样。
所以我的问题的答案是简单地将 [] 添加到我的代码中,即 cw.writerow([namelist3])
推荐阅读
- reactjs - 测试是否呈现具有所需 PropTypes 的 Material-UI withStyles 组件?
- docker-compose - AWS Build Project 服务 docker-compose build 命令不起作用
- rabbitmq - 对于两个不同的 RabbitMQ 服务器,将数据从交换移动到另一个交换的最佳方式是什么?
- mongodb - (MongoDB)向文档添加一个新字段,其值为嵌套子文档数组的总和
- qt - 来自十六进制文字 unicode 字符的 QByteArray
- c# - 如何在 ASP.NET Core 启动时定义 RestAPI 的路由?
- java - 确定按钮和字符串未显示在 JPanel 上
- reactjs - 导入css文件以响应事件
- python - 如何获得唯一的字典列表?
- hazelcast - Hazelcast / Eureka / Hazelcast-eureka-one 自定义实例信息