为什么我的数组的输出中有空格

未来小工具

我正在尝试从网站获取特定名称列表,以最终将它们输出到文件中。我正在解析的网站是这个

代码当然不完美,但令我困惑的是,为什么每组名称之间的输出中有空格?

 from urllib.request import urlopen
 from bs4 import BeautifulSoup as bS
 import re

# get the internals links  

    def get_internals():
        array=[]
        html = urlopen("http://127.0.0.1/www.prenom-marocain.com")
        soup = bS(html,"lxml")
        azlinks = soup.find("nav", {"class":"page-nav"}).findAll("a", {"href":re.compile("^p.*$")})
        for links in azlinks:
            array.append(links.attrs['href'])

        return array


    # The function for fetching the names 

    def fetch_name(url):
        array=[]
        html = urlopen("http://127.0.0.1/www.prenom-marocain.com/"+url)
        soup = bS(html, "lxml")
        for child in soup.findAll("ul", {"class":"arrow"}):
            array.append(child.getText())

        return array


    alpha_array = get_internals()


    first_names=[]

    for links in alpha_array:
        first_name += (fetch_name(links))


    for names in first_names:
        print(names)
    `

我怎样才能摆脱输出中的空格?这是 array.append 方法的正常行为吗?将所有内容存储在文件中的最佳方式是什么?提前致谢 !

安德烈·凯斯利

在您的函数中,fetch_name()您将空字符串添加到数组中(在没有任何名称的页面上,<ul class="arrow">是空字符串)。如果您可以将其过滤掉,则简单,这将打印所有没有空格的名称:

from urllib.request import urlopen
from bs4 import BeautifulSoup as bS
import re

# get the internals links

def get_internals():
    array=[]
    html = urlopen("http://www.prenom-marocain.com")
    soup = bS(html,"lxml")
    azlinks = soup.find("nav", {"class":"page-nav"}).findAll("a", {"href":re.compile("^p.*$")})
    for links in azlinks:
        array.append(links.attrs['href'])
    return array

# The function for fetching the names

def fetch_name(url):
    array=[]
    html = urlopen("http://www.prenom-marocain.com/"+url)
    soup = bS(html, "lxml")
    for child in soup.findAll("ul", {"class":"arrow"}):
        if not child.text.strip():
            break
        array.append(child.text.strip())
    return array

alpha_array = get_internals()

first_names=[]
for links in alpha_array:
    first_names += (fetch_name(links))

for names in first_names:
    print(names)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Bash数组,元素中有空格

Perl,为什么它在输出中有额外的空格

我的程序输出中有空格。知道如何摆脱它们吗?

为什么 SAS 程序的字符串中有空格(企业指南 8.3)

如果其中有空格,为什么此代码不起作用?

awk输出,第一列中有空格

为什么div周围有空格

为什么我的 SVG feTurbulence 输出中有细黑线?

为什么输出的最后一行有空格和p?

为什么wordpress输出<li>标记之间没有空格的菜单html

为什么我在Java String.split(regex)中有空令牌?

为什么我用WriteFile写入文件的每个字符之间都有空格?

带有空格的Bash多行输出,作为数组变量

请告诉我为什么我的输出中有一个“none”

为什么显示的数据没有空格?

为什么Roslyn生成没有空格的方法代码

目标中有空格的 SCP 命令

C#-路径中有空格

如何替换“ |〜|| ~~ ||〜||〜|” R中有空格?

ShellExecute,路径中有空格

珀尔。为什么数组输出工作两次?为什么输出中的单词之间有多个空格?

为什么我的 HTML 文本区域中有一个空格,当我有占位符时?

为什么Go中有数组?

为什么数组中有额外的值?

即使集合中有索引,为什么解释查询输出仍给我BasicCursor?

为什么我的程序集输出中有两个析构函数实现?

通过 cURL 发送时删除键中有空格的发送数组

如果安装路径中有空格,为什么反恐精英:条件零不能在 Windows 中播放介绍视频?

收到 cmd 错误,因为我的 Windows 用户名中有空格