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