Python 仅刮除<;p>;没有嵌入式<;a>;
我想把这篇文章的主体删去: 这通常是一个非常简单的find_all('p'),但我很难避免(p)中的(a)。例如,当正文中的一个单词超链接到另一个URL时,就会发生这种情况 我想得到的只是文本,没有网址。到目前为止,我已经:Python 仅刮除<;p>;没有嵌入式<;a>;,python,html,web-scraping,beautifulsoup,Python,Html,Web Scraping,Beautifulsoup,我想把这篇文章的主体删去: 这通常是一个非常简单的find_all('p'),但我很难避免(p)中的(a)。例如,当正文中的一个单词超链接到另一个URL时,就会发生这种情况 我想得到的只是文本,没有网址。到目前为止,我已经: from bs4 import BeautifulSoup import requests html = requests.get("https://www.cnbc.com/2017/12/07/pinterest-hires-former-facebook-exec
from bs4 import BeautifulSoup
import requests
html = requests.get("https://www.cnbc.com/2017/12/07/pinterest-hires-former-facebook-exec-gary-johnson-to-run-corporate-dev.html").text
soup = BeautifulSoup(html, 'html5lib')
all_paragraphs = soup.find_all('p')
如果没有(a)和随后的URL,我如何从所有(p)中提取文本
提前感谢您获取
p
中的所有文本(即使来自a
),但如果没有这些标记,请使用.text
或.get_text()
如果希望p
在a
中不包含文本,则必须在获取文本之前删除a
for p in all_paragraphs:
for a in p.find_all('a'):
a.extract()
print(p.text)
删除元素-所以删除
a
你只会得到p
或者你可能需要item.text
或item.get_text()
看看p
标签的某一部分:他将被[谷歌]老手乔恩·阿尔弗内斯
取代。在这一部分中,Google
位于a
标记内,没有该标记,句子就不清楚了。这是你想要的吗?
for p in all_paragraphs:
for a in p.find_all('a'):
a.extract()
print(p.text)