【问题标题】:What is the meaning of [:] in python [duplicate]python中[:]是什么意思[重复]
【发布时间】:2017-01-07 13:36:46
【问题描述】:

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,从锚标签中提取href= vaues,扫描在相对于列表中名字的特定位置,点击该链接并重复该过程多次并报告您找到的姓氏”。 示例问题:从http://python-data.dr-chuck.net/known_by_Fikret.html 开始 在位置 3 处找到链接(名字是 1)。按照那个链接。重复此过程 4 次。答案是您检索的姓氏。 姓名序列:Fikret Montgomery Mhairade Butchi Anayah 姓氏按顺序排列:Anayah

【问题讨论】:

  • 它从列表中删除所有元素。
  • @mgilson 你能解释一下这个程序是如何工作的,即最后 3 行吗?

标签: python python-2.7 web-scraping beautifulsoup


【解决方案1】:

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

这里的答案更深入地介绍了一般用途: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..

【讨论】:

  • 谢谢....你能解释一下这一行的作用吗“url = taglist[position-1].get('href', None)”。我是 python 新手....
  • stackoverflow.com/a/2068377/3213282 可能会有所帮助
  • 我没有得到“position-1”在做什么?
  • “位置”减1。
  • 是的,我知道,但为什么呢?
猜你喜欢
  • 2020-12-13
  • 2020-09-01
  • 2015-02-13
  • 2023-04-10
  • 2020-04-22
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多