尝试在特定div和sub div下提取数据

时间:2015-05-06 13:43:28

标签: python beautifulsoup

我想要得到它所以我可以打印书的标题和章节,但只有每本书和标题。

所以基本上 "雅各布的第一本书" 第1-7章

而不是迭代所有书籍。

这是页面布局(python代码中包含的url)

<dl>
  <dt>Title</dt>
  <dd>
    <dl>
      <dt>Sub Title</dt>
    </dl>
  </dd>
  <dt>Title 2</dt>
  <dd>
    <dl>
      <dt>Sub Title 2</dt>
    </dl>
  </dd>
</dl>
#this continues for Title 3, Sub title 3, etc etc

这是python代码

import requests
import bs4


scripture_url = 'http://scriptures.nephi.org/docbook/bom/'
response = requests.get(scripture_url)
soup = bs4.BeautifulSoup(response.text)

links = soup.select('dl dd dt')
for item in links:
    title = str(item.get_text()).split(' ', 1)[1]
    print title

这是输出

Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 19
Chapter 20
Chapter 21
Chapter 22
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 19
Chapter 20
Chapter 21
Chapter 22
Chapter 23
Chapter 24
Chapter 25
Chapter 26
Chapter 27
Chapter 28
Chapter 29
Chapter 30
Chapter 31
Chapter 32
Chapter 33
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 1
Chapter 1

3 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情。首先,找一本书,例如,标题为“雅各书”:

book_title = 'The Book of Jacob'
book = soup.find('a', text=book_title)
print book.text

然后选择<dd>作为书名的直接兄弟,并找到该<dd>元素中的所有相应章节:

links = book.parent.select('+ dd > dl > dt')
for item in links:
    title = str(item.get_text()).split(' ', 1)[1]
    print title

输出:

The Book of Jacob
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7

答案 1 :(得分:0)

刚刚截断数组中的最后2个,控件不是细粒度的,因为html标签中没有任何id或名称

links = soup.select('dl dd dt')
for item in links[:-2]:
    title = str(item.get_text()).split(' ', 1)[1]
    print title

答案 2 :(得分:0)

假设您知道它们始终是第一个和第二个值,您可以使用数组引用:

title = links[0];
subtitle = links[1];
相关问题