【问题标题】:Python Beautiful Soup stops parsingPython Beautiful Soup 停止解析
【发布时间】:2013-10-21 03:17:54
【问题描述】:

我尝试通过以下脚本解析附加的 text.txt 文件(使用 html 语法)。

#!/usr/bin/python3

import re
from bs4 import BeautifulSoup

pattern = re.compile("www.geocaching.com")
f=open("text.txt")
text=f.read()
f.close()
s = BeautifulSoup(text)
a = s.find_all(href=pattern)
print(len(a))
print (a[len(a)-1])

我的期望是所有标签都带有 href="www.geocaching.com",但我没有从附加的文件中得到所有标签。 最后一个是:

<a class="lnk " href="http://www.geocaching.com/geocache/GC3HWHJ_corse-known-unknown-2-view-on-ile-de-giraglia"><span>Corse known &amp; unknown 2 - View on Ile de Giraglia</span></a>

如果我删除第 626-674 行,只包含一些简单的 html 代码,我会得到接下来的两个,即最后一个是

<a class="lnk " href="http://www.geocaching.com/geocache/GC3MEDG_tour-genoise-dagnello"><span>TOUR GENOISE D'AGNELLO</span></a>

但我还是没有得到可以在 html 文件中手动找到的所有结果。

我使用的文件来自这里(我下载它以在本地使用它) https://www.geocaching.com/seek/nearest.aspx?lat=43.410333&lon=09.0476&dist=100

【问题讨论】:

  • 我用 BS3 试过你的代码,它也给了我最后一个链接
  • 如果我用 urllib2 打开链接,它的长度为 a = 42。

标签: python html-parsing beautifulsoup


【解决方案1】:

尝试通过以下方式使用 CSS 选择器:

from bs4 import BeautifulSoup

f = open("text.txt")
text = f.read()
f.close()

soup = BeautifulSoup(text)

# this find all the href containing the text "www.geocaching.com"
links =  soup.select('[href]~="www.geocaching.com"')

【讨论】:

    猜你喜欢
    • 2011-09-27
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多