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

标签 python web-scraping beautifulsoup

我对此很陌生,因此构建了一个脚本来学习如何抓取。 我在主索引页面中查询 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

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

关于python - 第一次运行后循环停止 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271298/

相关文章:

python - PyTorch 函数签名中的\* 是什么意思?

python - 无法读取 Javascript 文件 Electron JS 中未定义的属性 'join'

python - 想要隐藏 "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3" } from ping module output?

python - 使用python从div中抓取h3

python - 使用 BeautifulSoup 仅获取 URL 列表的第一个链接

python - 测试一个字符串,如果它是 Unicode,哪个 UTF 标准是并以字节为单位获取它的长度?

python - beautifulSoup 在 Python 网络抓取时不匹配 chrome inspect

html - 从网页中提取背景图像/解析 HTML+CSS

html - 使用 bs4 查找和删除 HTML5 data-* 属性

python 模块 BeautifulSoup importError