我正在使用bs4构建一个python3网络爬虫/刮刀。有些部分需要Reg Ex。我只想刮掉文字内容。我应该如何解析这样的事情:
<p> This is blah blah
<a class="wordpresslink" href="https://wordpress.com/" rel="generator nofollow">WordPress.com</a>
<a href="http://www.whatever.com/"><span class="s1">Example</span></a>
Like blah blah
</p>
我想要输出:
This is blah blah WordPress.com Example Like blah blah
我的代码到目前为止:
import urllib.request
from bs4 import BeautifulSoup
u='https://en.wikipedia.org/wiki/Adivasi'
r=urllib.request.urlopen(u)
soup=BeautifulSoup(r.read(),'html.parser')
res = [i.text.replace('\n', ' ').strip() for i in soup.find_all('p')]
for p in res:
print(p)
答案 0 :(得分:1)
使用BeautifulSoup解析器解析html文件。
>>> soup = BeautifulSoup(s)
>>> soup.find('p').text
u' This is blah blah\nWordPress.com\nExample\nLike blah blah\n'
>>> soup.find('p').text.replace('\n', ' ').strip()
u'This is blah blah WordPress.com Example Like blah blah'
如果还有更多,请使用find_all
[i.text.replace('\n', ' ').strip() for i in soup.find_all('p')]