How to extract text within HTML lists using beautifulsoup python

对着背影说爱祢 提交于 2020-01-14 05:05:05

问题


I'm trying to write a python program that can extract text between list in html. I would like to extract information like the book being hardcover and number of pages. Does anybody know the command for this operation?

<h2>Product Details</h2>
  <div class="content">
<ul>

<li><b>Hardcover:</b> 156 pages</li>

<li><b>Publisher:</b> Insight Editions; Har/Pstr edition (June 18, 2013)</li>

<li><b>Language:</b> English</li>

<li><b>ISBN-10:</b> 1608871827</li>
<li><b>ISBN-13:</b> 978-1608871827</li>

For parse other information I used:

definition in soup.findAll('span', {"class":'bb_price'}):
definition = definition.renderContents() 

but it does not work for this situation.


回答1:


Find the b tag by text and get the next_sibling.

Working example:

from bs4 import BeautifulSoup

data = """<h2>Product Details</h2>
  <div class="content">
<ul>

<li><b>Hardcover:</b> 156 pages</li>

<li><b>Publisher:</b> Insight Editions; Har/Pstr edition (June 18, 2013)</li>

<li><b>Language:</b> English</li>

<li><b>ISBN-10:</b> 1608871827</li>
<li><b>ISBN-13:</b> 978-1608871827</li></ul></div>"""

soup = BeautifulSoup(data)

print soup.find('b', text='Hardcover:').next_sibling
print soup.find('b', text='Publisher:').next_sibling

prints:

156 pages
Insight Editions; Har/Pstr edition (June 18, 2013)


来源:https://stackoverflow.com/questions/23303072/how-to-extract-text-within-html-lists-using-beautifulsoup-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!