【问题标题】:Python broken links after BeautifulSoupBeautifulSoup 之后的 Python 断开链接
【发布时间】:2018-04-22 12:15:29
【问题描述】:

我是 Python 的新手。刚刚为 Windows 安装它并尝试 HTML 抓取。 这是我的测试代码:

from bs4 import BeautifulSoup

html = 'text <a href="Transfert.php?Filename=myfile_x86&version=5&param=13" class="nav" style="color: #000000" title = "">Download</a> text'
print(html)

soup = BeautifulSoup(html, "html.parser")
for link in soup.find_all('a'):
    print(link.get('href'))

此代码返回已收集但损坏的链接:

Transfert.php?Filename=myfile_x86&version=5¶m=13

我该如何解决?

【问题讨论】:

  • 你想要什么输出?
  • 没有字符串格式的普通链接文本到符号。

标签: python windows beautifulsoup


【解决方案1】:

您正在向解析器提供无效的 HTML,正确的方法是包含 & 在 HTML 属性中的 URL 中将其转义为 &amp;amp;

只需将&amp;amp; 更改为&amp;amp;

html = 'text <a href="Transfert.php?Filename=myfile_x86&amp;version=5&amp;param=13" class="nav" style="color: #000000" title = "">Download</a> text'
soup = BeautifulSoup(html, "html.parser")

for link in soup.find_all('a'):
    print(link.get('href'))

输出:

Transfert.php?Filename=myfile_x86&version=5&param=13

它与html5liblxml 一起工作的原因是因为某些解析器可以比其他解析器更好地处理损坏的HTML。正如 cmets 中 Goyo 所提到的,您无法阻止其他人编写损坏的 HTML :)

这是对您的问题的一个很好的回答,详细解释了它:https://stackoverflow.com/a/26073147/4796844

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2021-04-09
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多