- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在做一个小项目,我在其中提取政治领导人在报纸上的出现。有时会提到一位政客,但没有 parent 或 child 有联系。 (我猜是由于语义错误的标记)。
所以我想创建一个函数,可以找到最近的链接,然后提取它。在下面的例子中,搜索字符串是 Rasmussen
,我想要的链接是:/307046
。
#-*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
tekst = '''
<li>
<div class="views-field-field-webrubrik-value">
<h3>
<a href="/307046">Claus Hjort spiller med mrkede kort</a>
</h3>
</div>
<div class="views-field-field-skribent-uid">
<div class="byline">Af: <span class="authors">Dennis Kristensen</span></div>
</div>
<div class="views-field-field-webteaser-value">
<div class="webteaser">Claus Hjort Frederiksens argumenter for at afvise
trepartsforhandlinger har ikke hold i virkeligheden. Hans rinde er nok
snarere at forberede det ideologiske grundlag for en Løkke Rasmussens
genkomst som statsministe
</div>
</div>
<span class="views-field-view-node">
<span class="actions">
<a href="/307046">Ls mere</a>
|
<a href="/307046/#comments">Kommentarer (4)</a>
</span>
</span>
</li>
'''
to_find = "Rasmussen"
soup = BeautifulSoup(tekst)
contexts = soup.find_all(text=re.compile(to_find))
def find_nearest(element, url, direction="both"):
"""Find the nearest link, relative to a text string.
When complete it will search up and down (parent, child),
and only X levels up down. These features are not implemented yet.
Will then return the link the fewest steps away from the
original element. Assumes we have already found an element"""
# Is the nearest link readily available?
# If so - this works and extracts the link.
if element.find_parents('a'):
for artikel_link in element.find_parents('a'):
link = artikel_link.get('href')
# sometimes the link is a relative link - sometimes it is not
if ("http" or "www") not in link:
link = url+link
return link
# But if the link is not readily available, we will go up
# This is (I think) where it goes wrong
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
if not element.find_parents('a'):
element = element.parent
# Print for debugging
print element #on the 2nd run (i.e <li> this finds <a href=/307056>
# So shouldn't it be caught as readily available above?
print u"Found: %s" % element.name
# the recursive call
find_nearest(element,url)
# run it
if contexts:
for a in contexts:
find_nearest( element=a, url="http://information.dk")
下面的直接调用有效:
print contexts[0].parent.parent.parent.a['href'].encode('utf-8')
作为引用,整个抱歉的代码都在 bitbucket 上:https://bitbucket.org/achristoffersen/politikere-i-medierne
(附注:使用 BeautifullSoup 4)
编辑:SimonSapin 要求我定义最近:“最近”是指距离搜索词在任一方向上嵌套层数最少的链接。在上面的文本中,由基于 drupal 的报纸站点生成的 a href
既不是找到搜索字符串的标签的直接父代也不是子代。所以 BeautifullSoup 找不到。
我怀疑“最少的字符数”通常也能奏效。在那种情况下,解决方案可以与 find 和 rfind 一起被破解 - 但我真的很想通过 BS 来做到这一点。因为这会起作用:contexts[0].parent.parent.parent.a['href'].encode('utf-8')
因此必须可以将其概括为脚本。
编辑:也许我应该强调我正在寻找 BeautifulSoup 解决方案。我认为,按照 @erik85 的建议,将 BS 与自定义/简单呼吸优先搜索相结合会很快变得困惑。
最佳答案
有人可能会想出一个适用于复制和粘贴的解决方案,您会认为这可以解决您的问题。不过,您的问题不是代码!这是你的策略。有一个称为“分而治之”的软件设计原则,您应该在重新设计代码时应用该原则:将将 HTML 字符串解释为树/图的代码与搜索最近的节点(可能是 breadth-first-search)分开。您不仅会学会设计更好的软件,而且您的问题可能会不复存在。
我认为你很聪明,可以自己解决这个问题,但我也想提供一个框架:
def parse_html(txt):
""" reads a string of html and returns a dict/list/tuple presentation"""
pass
def breadth_first_search(graph, start, end):
""" finds the shortest way from start to end
You can probably customize start and end to work well with the input you want
to provide. For implementation details see the link in the text above.
"""
pass
def find_nearest_link(html,name):
"""putting it all together"""
return breadth_first_search(parse_html(html),name,"link")
PS:这样做也适用另一个原则,但是从数学上讲:假设有一个问题您不知道解决方案(找到靠近所选子字符串的链接)并且有一组问题您知道解决方案到(图形遍历),然后尝试转换你的问题以匹配你可以解决的问题组,这样你就可以只使用基本的解决方案模式(甚至可能已经在你选择的语言/框架中实现了)你就完成了.
关于python - 查找与 BeautifulSoup(python)最近的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11776157/
我需要获取过去 24 小时的记录,但不能像这样按小时分组: SELECT HOUR(CompDate) AS hour, COUNT(1) AS action FROM mytable WHERE (
我们有一个自动完成列表,当您向某人发送电子邮件时会填充该列表,这一切都很好,直到列表变得非常大,您需要输入越来越多的地址才能找到您想要的地址, 这违背了自动完成的目的 我在想应该添加一些逻辑,以便自动
我在 android 的锁屏上工作我们如何禁用导航软按钮,已经尝试了所有方法,systemoverlay但它不起作用,在按下主页按钮时它会终止服务和 Activity 。 最佳答案 后退按钮可以通过覆
我有一个报告创建时间为 2016-05-30,现在我需要从报告时间开始的最后 7 天。我怎样才能使用时刻? report_create_time = moment('2016-05-30').form
我想找出向量中最接近的三个数字。 就像是 v = c(10,23,25,26,38,50) c = findClosest(v,3) c 23 25 26 我试过 sort(colSums(as.ma
考虑以下表结构: id speed 1 100 2 200 3 300 4 400 5 500 考虑以下查询:"SELECT * FROM records WHERE
我正在开发一个依赖 YouTube 直播和实时聊天(也来自 YouTube)的网络应用。事情进展顺利,突然嵌入的聊天功能无法在移动设备上运行。 我试图在我这边找到一个错误或一些无效的配置,但我找不到。
我正在制作一个 React Native 应用程序,它有一个安全部分,用户必须在其中输入密码才能解锁 protected 内容。问题是,当用户在锁定该部分之前切换到另一个应用程序时,将生成屏幕截图以及
我有一条 SQL 语句 (SQL Server Management Studio),我通过仪表板软件将数据传递到 where 语句中。用户可以选择年份(2013 年或现在的 2014 年)和月份(作
我有一个脚本可以添加一组行,使您能够在 SharePoint 列表表单中捕获其他访问者的信息。我有两个 anchor 标记,一个用于添加,另一个用于删除。当我添加一个新的访问者时它有效,当我删除访问者
我正在学习斯坦福 iOS 类(class),我有一个问题,我认为与最近的更新有关。这是代码部分: func evaluate(ops: [Op]) -> (result: Double?,remain
我注意到我的应用有一个奇怪的行为。每当我按下主页按钮时,我的应用程序就会被杀死。我没有在应用程序堆栈中看到该应用程序。我可以看到之前启动的其他应用程序。最初我怀疑 android:launchMode
我需要获取过去 7 天内的所有付费和临时条目,但我总是收到所有退回的内容。我不确定我做错了什么,我已经阅读了这里的很多帖子,但无法理解它是什么。 MySQL 5.6(如果它与我一直在做的事情有什么不同
我的表有一列以 mysql time() 格式格式化。 当它是一个值分配给名为 $preRemainOt 的 php 变量时我想重新安排到最近的 15 分钟 function roundTime($w
我想获取过去 7 天内每天每个产品的最后时间戳。数据库中有数千条记录。我怎样才能通过查询来做到这一点。大约有 25 种不同的产品,每种产品每天大约有 50 个时间戳。 表:构建数据 'Timesta
我现在的代码正在从 SQL 中获取移动应用程序中的数据,首先添加显示,我需要将其设置为在我的 Android 应用程序中显示最后添加的第一个。我有如下所示的 api 代码,最新的是根据我的要求显示的,
我有一张 table ,说 table 的描述为: | ID | SNO | c1 | c2 | c3 | ___________________________________ |
我有两个大小相等的向量,例如 A=[2.29 2.56 2.77 2.90 2.05] and B=[2.34 2.62 2.67 2.44 2.52]. 我有兴趣在两个相同大小的向量 A 和 B 中
之前,我在这里发布了一个问题,询问有关如何从驱动器读取和写入数据的建议,而不是通过像“aaa.txt”这样的文件标签,而只是扇区..我被建议尝试阅读和写作....但新问题出现了……毛茸茸的参数 int
我想删除在给定时间段内未登录的用户,但我稍后会根据结果选择时间段。 所以我需要报告,其中我将收到过去 1 个月、2 个月...... n 个月内未登录的用户数量。 我不太清楚如何在单个 mysql 查
我是一名优秀的程序员,十分优秀!