Skip to main content
 首页 » 编程设计

python之第一次运行后循环停止之Python

2025年05月04日15mq0036

我对此很陌生,因此构建了一个脚本来学习如何抓取。 我在主索引页面中查询 URL 列表,然后包含我想要的联系信息。

我成功地将索引列表放入一个集合中,然后尝试使用两个函数对其进行迭代(我相信有更好的方法可以做到这一点)。第一次迭代后,它停止了,我根本不明白为什么。任何指针表示赞赏。

import requests 
from bs4 import BeautifulSoup 
 
linkset = set() 
url = "http://someurl.com/venues" 
r = requests.get(url) 
soup = BeautifulSoup(r.content, "lxml") 
 
base_url = "http://someurl.com/uk/" 
links = soup.find_all("a", class_="supplier-link") 
 
 
# A function to get the links from the top level directory. 
def get_venue_link_list(links): 
    for link in links: 
        linkset.add(link.get("href")) 
        return linkset 
 
#get_venue_link_list(links) 
# When I test by printing linkset, I get the list of unique URL's. 
# This works as expected. 
#print linkset 
 
# A function to go retrieve contact 
 
def go_retrieve_contact(link_value): 
    for i in link_value: 
        link = i 
        venue_link = base_url + link 
        venue_request = requests.get(venue_link) 
        venue_soup = BeautifulSoup(venue_request.content, "lxml") 
        info = venue_soup.find_all("section", {"class": "findout"}) 
        header = venue_soup.find_all("div", {"id": "supplier-header-desktop"}) 
        go_get_info(info) 
# Email, Phone and Website was nested in one div so it was a little easier to get. 
# Will need to use a different div for address and social media names. 
 
def go_get_info(info): 
    for item in info: 
        print "%s" % ((item.contents[3].find_all("span", {"class": "text"})[0].text)).strip() 
        print "%s" % ((item.contents[3].find_all("span", {"class": "text"})[1].text)).strip() 
        print "%s" % ((item.contents[3].find_all("span", {"class": "text"})[2].text)).strip() 
        #Lets comment out this next nested loop until I fix the above. 
        #for item in header: 
            #print item.contents[1].text 
 
go_retrieve_contact(get_venue_link_list(links)) 

请您参考如下方法:

return 导致函数完全退出。按照你编写它的方式,你已经告诉函数在第一次迭代后立即返回 - 所以它会停止也就不足为奇了。 :)

这是一个缩进问题 - 你真正想要的是:

def get_venue_link_list(links): 
    for link in links: 
        linkset.add(link.get("href")) 
    return linkset 

这让循环先完成,然后退出。