Python:解析关键字之间的文本

标签 python regex web-scraping beautifulsoup

我正在寻求使用 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>

(这是我要解析的内容,在<h4><p>之间) <p align="justify"></p>

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

最佳答案

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

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)

关于Python:解析关键字之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33382806/

相关文章:

python - 使用 Django 模板标签 'slice' 切片 pandas 数据框?

python - 如何在Python文本字符串中找到省略号?

javascript - 正则表达式删除逗号分隔字符串中的前导零

go - 使用 gocolly 抓取时如何在 html 表格单元格中保留换行符

python - Scrapy,URL 上的哈希标签

python - 为什么 compute() 方法对于 Dask 数据帧很慢,而 head() 方法很快?

python - matplotlib 轴箭头提示

python - 如何在每次出现时保留 numpy 数组的最新元素

javascript - 找出 Discord webhooks 链接的正则表达式

java - 如何在 Java 中检索 "inspected source code"(Google chrome)?