【问题标题】:How to scrape paragraphs from websites using python? [duplicate]如何使用 python 从网站上抓取段落? [复制]
【发布时间】:2020-10-22 16:46:38
【问题描述】:

我正在尝试从这个网站制作一个题库

https://www.neetprep.com/questions/851-Botany/7918-Living-World?courseId=386

我正在使用以下代码

from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
import re

my_url = 'https://www.neetprep.com/questions/851-Botany/7918-Living-World?courseId=386'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")

containers = page_soup.findAll("span",{"class": "-PmH"})
print(soup.prettify(containers[0]))

我的输出如下:

<span class="-PmH" id="questionUXVlc3Rpb246NzE3MQ==">
 <p>
  The third name in trinomial nomenclature is
 </p>
 <p>
  (1) Species
 </p>
 <p>
  (2) Subgenus
 </p>
 <p>
  (3) Subspecies
 </p>
 <p>
  (4) Ecotype
 </p>
</span>

现在如何修改代码以仅将问题和选项作为输出文本。

对于这个问题,我的输出应该是

The third name in trinomial nomenclature is
(1) Species
(2) Subgenus
(3) Subspecies
(4) Ecotype

因此我想从我的输出中删除&lt;p&gt;&lt;/p&gt; 标签。

【问题讨论】:

  • 您可以使用 beautifulsoup 中的 get_text() 方法。这将删除所有 HTML 标记,只为您提供文本。
  • for p in containers[0].findAll('p'): print(p.text)。你不需要prettify

标签: python


【解决方案1】:

尝试改变:

print(soup.prettify(containers[0]))

print(containers[0].text.split("\n"))

【讨论】:

  • 你甚至不需要换行符
  • 只有容器[0].text 给出了我想要的输出。非常感谢!
猜你喜欢
  • 2017-02-13
  • 2016-04-06
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2017-11-26
  • 2020-03-09
相关资源
最近更新 更多