Skip to main content
 首页 » 编程设计

python之在 Python 中跟踪链接

2025年05月04日18emanlee

我必须编写一个程序,从这个链接(http://python-data.dr-chuck.net/known_by_Maira.html)中读取 HTML,从 anchor 标签中提取 href= 值,扫描相对于名字在特定位置的标签列出,点击该链接并重复该过程多次并报告您找到的姓氏。

我应该找到位置 18 的链接(名字是 1),点击该链接并重复此过程 7 次。答案是我检索到的姓氏。

这是我找到的代码,它工作得很好。

import urllib 
 
from BeautifulSoup import * 
 
url = raw_input("Enter URL: ") 
count = int(raw_input("Enter count: ")) 
position = int(raw_input("Enter position: ")) 
 
names = [] 
 
while count > 0: 
    print "retrieving: {0}".format(url) 
    page = urllib.urlopen(url) 
    soup = BeautifulSoup(page) 
    tag = soup('a') 
    name = tag[position-1].string 
    names.append(name) 
    url = tag[position-1]['href'] 
    count -= 1 
 
print names[-1] 

如果有人能像您向 10 岁的 child 一样向我解释 while 循环内部发生了什么,我将不胜感激。我是 Python 的新手,非常感谢您的指导。

请您参考如下方法:

while count > 0:                         # because of `count -= 1` below, 
                                         # will run loop count times 
 
    print "retrieving: {0}".format(url)  # just prints out the next web page 
                                         # you are going to get 
 
    page = urllib.urlopen(url)           # urls reference web pages (well, 
                                         # many types of web content but 
                                         # we'll stick with web pages) 
 
    soup = BeautifulSoup(page)           # web pages are frequently written 
                                         # in html which can be messy. this 
                                         # package "unmessifies" it 
 
    tag = soup('a')                      # in html you can highlight text and 
                                         # reference other web pages with <a> 
                                         # tags. this get all of the <a> tags 
                                         # in a list 
 
    name = tag[position-1].string        # This gets the <a> tag at position-1 
                                         # and then gets its text value 
 
    names.append(name)                   # this puts that value in your own 
                                         # list. 
 
    url = tag[position-1]['href']        # html tags can have attributes. On 
                                         # and <a> tag, the href="something" 
                                         # attribute references another web 
                                         # page. You store it in `url` so that 
                                         # its the page you grab on the next 
                                         # iteration of the loop. 
    count -= 1