gpt4 book ai didi

python - £ 在 urllib2 和 Beautiful Soup 中显示

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:36 25 4
gpt4 key购买 nike

我正在尝试用 Python 编写一个小型网络抓取工具,但我想我遇到了编码问题。我正在尝试抓取 http://www.resident-music.com/tickets (特别是页面上的表格)- 一行可能看起来像这样 -

    <tr>
<td style="width:64.9%;height:11px;">
<p><strong>the great escape 2017&nbsp; local early bird tickets, selling fast</strong></p>
</td>
<td style="width:13.1%;height:11px;">
<p><strong>18<sup>th</sup>&ndash; 20<sup>th</sup> may</strong></p>
</td>
<td style="width:15.42%;height:11px;">
<p><strong>various</strong></p>
</td>
<td style="width:6.58%;height:11px;">
<p><strong>&pound;55.00</strong></p>
</td>
</tr>

我实际上是在尝试将 £55.00 替换为 55 英镑和任何其他“非文本”内容。

我已经尝试了一些不同的编码方式,你可以使用 beautifulsoup 和 urllib2 - 无济于事,我想我只是做错了。

谢谢

最佳答案

你想取消转义你可以在 python3 中使用 html.unescape 的 html:

In [14]: from html import unescape

In [15]: h = """<tr>
....: <td style="width:64.9%;height:11px;">
....: <p><strong>the great escape 2017&nbsp; local early bird tickets, selling fast</strong></p>
....: </td>
....: <td style="width:13.1%;height:11px;">
....: <p><strong>18<sup>th</sup>&ndash; 20<sup>th</sup> may</strong></p>
....: </td>
....: <td style="width:15.42%;height:11px;">
....: <p><strong>various</strong></p>
....: </td>
....: <td style="width:6.58%;height:11px;">
....: <p><strong>&pound;55.00</strong></p>
....: </td>
....: </tr>"""

In [16]:

In [16]: print(unescape(h))
<tr>
<td style="width:64.9%;height:11px;">
<p><strong>the great escape 2017  local early bird tickets, selling fast</strong></p>
</td>
<td style="width:13.1%;height:11px;">
<p><strong>18<sup>th</sup>– 20<sup>th</sup> may</strong></p>
</td>
<td style="width:15.42%;height:11px;">
<p><strong>various</strong></p>
</td>
<td style="width:6.58%;height:11px;">
<p><strong>£55.00</strong></p>
</td>
</tr>

对于 python2 使用:

In [6]: from html.parser import HTMLParser

In [7]: unescape = HTMLParser().unescape

In [8]: print(unescape(h))
<tr>
<td style="width:64.9%;height:11px;">
<p><strong>the great escape 2017  local early bird tickets, selling fast</strong></p>
</td>
<td style="width:13.1%;height:11px;">
<p><strong>18<sup>th</sup>– 20<sup>th</sup> may</strong></p>
</td>
<td style="width:15.42%;height:11px;">
<p><strong>various</strong></p>
</td>
<td style="width:6.58%;height:11px;">
<p><strong>£55.00</strong></p>
</td>

您可以看到两者都正确地对所有实体进行了转义,而不仅仅是井号。

关于python - £ 在 urllib2 和 Beautiful Soup 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com