【问题标题】:Getting the text from links inside a td with BeautifulSoup in Python 2.7在 Python 2.7 中使用 BeautifulSoup 从 td 中的链接获取文本
【发布时间】:2016-09-09 09:26:58
【问题描述】:

我试图让BeautifulSoup通过抓取获取所有位置名称的列表,我曾经使用以下方法:

locs = LOOPED.findAll("td", {"class": "max use"})

以前适用于 HTML

<td class="max use" style="">London</td>

但是 HTML 已更改为,不再返回 London

<td class="max use" style="">
    <div class="notranslate">
        <span><a data-title="View Location" href="/location/uk/gb/london/">London</a></span> <span class="extra hidden">(DEFAULT)</span>
    </div>
</td>

编辑:如果我打印 locs,我会得到如下列表:

&lt;td class="max use" style=""&gt;\n&lt;div class="notranslate"&gt;\n&lt;span&gt;&lt;a data-title="View Location" href="/location/uk/gb/london/"&gt;London&lt;/a&gt;&lt;/span&gt; &lt;span class="extra hidden"&gt;(DEFAULT)&lt;/span&gt;\n&lt;/div&gt;\n&lt;/td&gt;, &lt;td class="max use" style=""&gt;\n&lt;div class="notranslate"&gt;\n&lt;span&gt;&lt;a data-title="View Location" href="/location/uk/gb/manchester/"&gt;Manchester&lt;/a&gt;&lt;/span&gt; &lt;span class="extra hidden"&gt;(DEFAULT)&lt;/span&gt;\n&lt;/div&gt;\n&lt;/td&gt;, &lt;td class="max use" style=""&gt;\n&lt;div class="notranslate"&gt;\n&lt;span&gt;&lt;a data-title="View Location" href="/location/uk/gb/liverpool/"&gt;Liverpool&lt;/a&gt;&lt;/span&gt; &lt;span class="extra hidden"&gt;(NA)&lt;/span&gt;\n&lt;/div&gt;\n&lt;/td&gt;]

你可以看到有 3 个不同的位置,从上面我希望看到[London, Manchester, Liverpool] 的列表

我认为我应该使用类似的东西:

locs = LOOPED.findAll("td", {"class": "max use"})
locs = locs.findAll('a')[1]
print locs.text

但这只会与

AttributeError: 'ResultSet' 对象没有属性 'findAll'

我不知道如何让Beautifulsoup 重新搜索超链接文本...

【问题讨论】:

  • 是不是因为你的'a'不是直接在'td'下面,我猜你需要先通过'div'然后'span'。
  • @AvinashRaj 是的,如果我在locs = LOOPED.findAll("td", {"class": "max use"}) 之后打印locs,它会打印在divspan 下具有链接的HTML。
  • 嘿,这里的问题是locslist。如果需要来自locs 中每个位置的文本,则必须遍历locs 并打印每个位置的文本。

标签: python python-2.7 beautifulsoup


【解决方案1】:

试试这个:

tag = LOOPED.findAll('td') #all "td" tag in a list
tag_a = tag[0].find('a')
print tag_a.text

【讨论】:

  • 这对我不起作用,它需要先搜索max use类,然后再寻找a
【解决方案2】:

一种对未来 HTML 结构更改更稳健的方法是获取每个 td 元素内的所有文本,如 this answer 中所述:

locs = LOOPED.findAll("td", {"class": "max use"})
for loc in locs:
    print ''.join(loc.findAll(text=True))

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多