我使用的是python-3、bs4和以下代码片段
for result in results:
# to find the src tag contents
# .split('/')[-1:] removes all the text up to the final / and returns the name of the img file
img_elem = result.a.img['src'].split('/')[-1:]返回的文本为img_elem = ['vwTiguan_001.jpg']
我找不到打印img_elem = vwTiguan_001.jpg的方法,因此只删除了['和']
谢谢你们汤米。
发布于 2020-05-27 19:46:19
尝试使用名为ntpath的python模块,而不是对整个路径进行拆分来获取文件名
>>> import ntpath
>>> ntpath.basename("/a/b/c.txt")
'c.txt'发布于 2020-05-27 18:30:33
您可以使用replace方法。只需将括号替换为空字符串。
des = img_elem.replace("[", "").replace("]", "")发布于 2020-05-27 20:28:02
删除冒号
result.a.img['src']的类型是str,一个字符串。您正在调用str.split()方法,该方法返回一个列表。这就是那些括号。
在Python中,list类型没有返回最后一个元素的方法。因此,您只能使用直接访问(使用[i]表示法)。正如您所怀疑的,有一个技巧可以在不知道列表中有多少个元素的情况下获取列表的最后一个元素,即list[-1],不带冒号(:),如Jon Clements suggested。剩下的就是
img_elem = result.a.img['src'].split('/')[-1]解包
另一种方法是使用解包/解构,如下所示
elements = [1, 2, 3, 4, 5]
first_element, *after_first = elements # first_element=1, after_first=[2,3,4,5]
*before_last, last_element = elements # before_last=[1,2,3,4], last_element=5
first_element, *middle, last_element = elements在这些示例中,after_first、before_last和middle都拥有一个列表(请注意*),而它们的对应部分拥有项本身,而不是包装在列表中。
在你的例子中,你会有这样的东西
*rest_of_the_path, img_elem = result.a.img['src'].split('/')https://stackoverflow.com/questions/62040915
复制相似问题