【问题标题】:Python: parsing texts between keywordsPython:解析关键字之间的文本
【发布时间】:2016-01-27 17:45:18
【问题描述】:

我正在寻求使用 BeautifulSoup 来解析一种网页上的文本,代码如下:

import urllib 
import re

html = urllib.urlopen('http://english.hani.co.kr/arti/english_edition/e_national/714507.html').read()
content= str(soup.find("div",  class_="article-contents"))

所以我的目标是至少解析出第一段中的第一句话或前几句话。

因为段落没有被<p> 标签包围,所以到目前为止我最好的策略是在content 中找到</h4><p> 之间的文本(发生这种情况成为第一段)

目标文本如下所示:

<div class="article-contents">
<div class="article-alignC">
<table class="photo-view-area">
<tr>
<td>
<img alt="" border="0" src="http://img.hani.co.kr/imgdb/resize/2015/1024/00542577201_20151024.JPG" style="width:590px;"/>
</td>
</tr>
</table>
</div>
<h4></h4>

(这是我要解析的内容,在&lt;h4&gt;&lt;p&gt; 之间) &lt;p align="justify"&gt;&lt;/p&gt;

我正在尝试直接在 BeautifulSoup 上执行此操作或使用正则表达式,但到目前为止仍然不成功。

【问题讨论】:

    标签: python regex web-scraping beautifulsoup


    【解决方案1】:

    找到h4元素并使用find_next_sibling()找到第一个下一个文本兄弟

    h4 = soup.select_one("div.article-contents > h4")
    print(h4.find_next_sibling(text=True))
    

    打印:

    US scholar argues that any government attempt to impose single view of history is misguided On Oct. 19, the Hankyoreh’s Washington correspondent conducted on interview with phone and email with William North, chair of the history department at Carleton University in Minnesota. The main topic of the discussion was the efforts of the administration of South Korean President Park Geun-hye to take over the production of history textbooks. 
    

    嗯,实际上,在这里使用.next_sibling 就足够了:

    print(h4.next_sibling)
    

    【讨论】:

    • 非常感谢,虽然这里没有必要,但也很高兴知道 (text=true)!
    • 一个额外的问题:有没有办法在相同的设置下返回第二段而不是第一段?
    • @carl_pch 尚未测试,但请尝试一下:h4.find_next_siblings(text=True)[1]
    • 这太棒了!我读到了迭代的“next_siblings”,但没有意识到 [#] 可以指示多少次(如果我理解正确的话)。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多