Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用BeautifulSoup/Python从html文件中提取文本_Python_Html_Beautifulsoup - Fatal编程技术网

使用BeautifulSoup/Python从html文件中提取文本

使用BeautifulSoup/Python从html文件中提取文本,python,html,beautifulsoup,Python,Html,Beautifulsoup,我试图从html文件中提取文本。 html文件如下所示: 我想从最后一个span标记中提取最后一个文本。 在第一行中,它将是class=“toctext”之后的“Baden-Würtemberg”,然后将其放入python列表中 在Python中,我尝试了以下方法: names = soup.find_all("span",{"class":"toctext"}) 我的输出是这个列表: [<span class="toctext">Baden-Württemberg&

我试图从html文件中提取文本。
html
文件如下所示:

  • 我想从最后一个
    span
    标记中提取最后一个文本。 在第一行中,它将是
    class=“toctext”
    之后的“Baden-Würtemberg”,然后将其放入python列表中

    在Python中,我尝试了以下方法:

    names = soup.find_all("span",{"class":"toctext"})
    
    我的输出是这个
    列表

    [<span class="toctext">Baden-Württemberg</span>, <span class="toctext">Bayern</span>, <span class="toctext">Berlin</span>]
    
    [Baden-Württemberg,拜仁,柏林]
    
    那么,如何只提取标签之间的文本呢


    多亏了all

    find\u all
    方法返回一个列表。迭代列表以获取文本

    for name in names:
        print(name.text)
    
    返回:

    Baden-Württemberg
    Bayern
    Berlin
    
    内置的python
    dir()
    type()
    方法总是可以方便地检查对象

    print(dir(names))
    
    [...,
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     '__weakref__',
     'append',
     'clear',
     'copy',
     'count',
     'extend',
     'index',
     'insert',
     'pop',
     'remove',
     'reverse',
     'sort',
     'source']
    

    通过理解列表,您可以执行以下操作:

    names = soup.find_all("span",{"class":"toctext"})
    print([x.text for x in names])