【问题标题】:Empty variable when extracting 'a' tags using BeautifulSoup in Python在 Python 中使用 BeautifulSoup 提取“a”标签时的空变量
【发布时间】:2020-10-21 10:35:17
【问题描述】:

我需要从转储中提取所有链接:

import requests
from bs4 import BeautifulSoup

index = requests.get('https://dumps.wikimedia.org/backup-index.html').text
soup_index = BeautifulSoup(index, 'html.parser')
dumps = [a['href'] for a in soup_index.find_all('a')
        if a.has_attr('href') and a.text[:-1].isdigit()]

但是我得到一个空的转储变量。

我做错了什么?

【问题讨论】:

  • 可能是因为没有a.text,它的最后一个字符是数字。
  • @JackFleeting 我该如何解决?这是示例之一'zhwiki'
  • 是的,许多<a> 节点都有文本,但文本不以.isdigit() 要求的数字结尾。所以没有办法解决这个问题。如果需要,您可以删除条件并打印文本。
  • 另外,您的预期输出究竟是什么?
  • @JackFleeting 我正在尝试提取链接

标签: python-3.x beautifulsoup html-parsing list-comprehension


【解决方案1】:

您可能正在寻找这样的东西:

targets = soup_index.find_all('a',href=True)
for target in targets:
    print(target,target.text)

输出:

<a href="angwikibooks/20200701">angwikibooks</a> angwikibooks
<a href="huwikisource/20200701">huwikisource</a> huwikisource
<a href="cswikiquote/20200701">cswikiquote</a> cswikiquote
<a href="cawikibooks/20200701">cawikibooks</a> cawikibooks

等等

【讨论】:

    猜你喜欢
    • 2016-04-01
    • 2018-06-14
    • 2021-12-22
    • 2018-12-12
    • 2022-01-13
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多