Python3.5 BeautifulSoup4从div中的'p'获取文本

use*_*906 5 html beautifulsoup python-3.x python-requests

我试图从div类'caselawcontent searchable-content'中提取所有文本.此代码只打印HTML而不包含网页中的文本.得到文本我错过了什么?

以下链接位于'finteredcasesdoc.text'文件中:http://caselaw.findlaw.com/mo-court-of-appeals/1021163.html

import requests
from bs4 import BeautifulSoup

with open('filteredcasesdoc.txt', 'r') as openfile1:

    for line in openfile1:
                rulingpage = requests.get(line).text
                soup = BeautifulSoup(rulingpage, 'html.parser')
                doctext = soup.find('div', class_='caselawcontent searchable-content')
                print (doctext)
Run Code Online (Sandbox Code Playgroud)

Yon*_*ono 5

from bs4 import BeautifulSoup
import requests

url = 'http://caselaw.findlaw.com/mo-court-of-appeals/1021163.html'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
Run Code Online (Sandbox Code Playgroud)

我添加了一个更可靠的.find 方法(键

whole_section = soup.find('div',{'class':'caselawcontent searchable-content'})


the_title = whole_section.center.h2
#e.g. Missouri Court of Appeals,Southern District,Division Two.
second_title = whole_section.center.h3.p
#e.g. STATE of Missouri, Plaintiff-Appellant v....
number_text = whole_section.center.h3.next_sibling.next_sibling
#e.g.
the_date = number_text.next_sibling.next_sibling
#authors
authors = whole_section.center.next_sibling
para = whole_section.findAll('p')[1:]
#Because we don't want the paragraph h3.p.
# we could aslso do findAll('p',recursive=False) doesnt pickup children
Run Code Online (Sandbox Code Playgroud)

基本上,我已经剖析了整棵树 的段落(例如 Main text, the var para),你必须循环 print(authors)

# and you can add .text (e.g. print(authors.text) to get the text without the tag. 
# or a simple function that returns only the text 
def rettext(something):
    return something.text
#Usage: print(rettext(authorts)) 
Run Code Online (Sandbox Code Playgroud)