python - [ :] in python 是什么意思

标签 python python-2.7 web-scraping beautifulsoup

<分区>

del taglist[:] 行在下面的代码中做了什么?

import urllib
from bs4 import BeautifulSoup
taglist=list()
url=raw_input("Enter URL: ")
count=int(raw_input("Enter count:"))
position=int(raw_input("Enter position:"))
for i in range(count):
    print "Retrieving:",url
    html=urllib.urlopen(url).read()
    soup=BeautifulSoup(html)
    tags=soup('a')
    for tag in tags:
        taglist.append(tag)
    url = taglist[position-1].get('href', None)
    del taglist[:]
print "Retrieving:",url

问题是“编写一个扩展 http://www.pythonlearn.com/code/urllinks.py 的 Python 程序。该程序将使用 urllib 从下面的数据文件中读取 HTML,从 anchor 标记中提取 href= vaues,扫描位于相对于列表中名字的特定位置,点击该链接并重复该过程多次并报告您找到的姓氏”。 示例问题:开始于 http://python-data.dr-chuck.net/known_by_Fikret.html 找到位置 3 的链接(名字是 1)。按照该链接。重复此过程 4 次。答案是您检索到的姓氏。 姓名顺序:Fikret Montgomery Mhairade Butchi Anayah 姓氏按顺序:Anayah

最佳答案

[:] 是数组中每个元素的数组切片语法。

这里的答案更深入地介绍了一般用途:Explain Python's slice notation

del arr # Deletes the array itself
del arr[:]  # Deletes all the elements in the array
del arr[2]  # Deletes the second element in the array
del arr[1:]  # etc..

关于python - [ :] in python 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241529/

相关文章:

python - Xpath:如何获取 <p> 标签内 <a> 标签的文本

python - 将函数应用于多索引多列数据帧的 Pythonic 方法是什么?

python-2.7 - 尝试在python中播放AudioSegment时权限被拒绝

python - 为什么模拟在调用时忽略传递给模拟方法的实例/对象?

python - for else语句用法及含义

python - 生成带日期的随机时间序列数据

python - 如何使用 Beautiful Soup(模态容器)抓取 HTML 数据端点

python - 在 Python 中屏幕抓取基于 Javascript 的网页

python - MySQLdb 没有插入,_mysql 没问题

python - 在 Anaconda 和 Anaconda3 之间切换