【问题标题】:Select multiple elements with BeautifulSoup and manage them individually使用 BeautifulSoup 选择多个元素并单独管理它们
【发布时间】:2019-02-19 16:17:55
【问题描述】:

我正在使用 BeautifulSoup 来解析诗歌网页。诗歌分为h3 用于诗歌标题,.line 用于诗歌的每一行。我可以获取这两个元素并将它们添加到列表中。但我想将h3 操作为大写并指示换行符,然后将其插入到行列表中。

    linesArr = []
    for lines in full_text:
        booktitles = lines.select('h3')
        for booktitle in booktitles:
            linesArr.append(booktitle.text.upper())
            linesArr.append('')
        for line in lines.select('h3, .line'):
            linesArr.append(line.text)

此代码将所有书名附加到列表的开头,然后继续获取h3.line 项目。我试过插入这样的代码:

    linesArr = []
    for lines in full_text:
        for line in lines.select('h3, .line'):
            if line.find('h3'):
                linesArr.append(line.text.upper())
                linesArr.append('')
            else:
                linesArr.append(line.text)

【问题讨论】:

标签: python web-scraping beautifulsoup html-parsing


【解决方案1】:

我不确定您要做什么,但是通过这种方式,您可以获得一个带有大写标题和所有行的数组:

#!/usr/bin/python3
# coding: utf8

from bs4 import BeautifulSoup
import requests

page = requests.get("https://quod.lib.umich.edu/c/cme/CT/1:1?rgn=div2;view=fulltext")
soup = BeautifulSoup(page.text, 'html.parser')

title = soup.find('h3')
full_lines = soup.find_all('div',{'class':'line'})

linesArr = []
linesArr.append(title.get_text().upper())
for line in full_lines:
    linesArr.append(line.get_text())

# Print full array with the title and text
print(linesArr)

# Print text here with line break
for linea in linesArr:
    print(linea + '\n')

【讨论】:

  • 我没有足够的声望点来支持您的回答,但谢谢。做两个单独的汤电话是个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2014-11-03
相关资源
最近更新 更多