【问题标题】:Python web scraping using BeautifulSoup, how to merge two <p> text into one element of listPython网页抓取使用BeautifulSoup,如何将两个<p>文本合并到一个列表元素中
【发布时间】:2019-02-07 00:53:36
【问题描述】:

我使用 BeautifulSoup 进行网页抓取,将结果放入列表中, html 显示如下:

<p class="attrgroup">
            <span><b>2013 Volkswagen Passat</b></span>
            <br>
    </p>
<p class="attrgroup">
            <span>condition: <b>excellent</b></span>
            <br>
    </p>  
           
我的代码是:
title=[]
text=[]
for newpage in list:
webpage = urlopen(newpage).read()
soup = BeautifulSoup(webpage,'html.parser')
header=soup.find_all("span",attrs={"id":"titletextonly"})
info = soup.find_all("p",attrs={"class":"attrgroup"})
for h in header:
        title.append(h.get_text())
for m in info:
        text.append(m.get_text())

文本列表结果为: ["2013 Volkswagen Passat","状态:优秀"]

但我想要这样的结果: [“2013大众帕萨特状态:优秀”]

将两个文本放入列表时如何合并?请帮忙!!!

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    使用列表的join()函数。

    title = []
    for h in header:
            title.append(h.get_text())
    title = ''.join([title])
    

    否则,将元素添加到列表而不是文本,并使用list comprehension 加入文本。

    title = []
    for h in header:
            title.append(h)
    title = ''.join([i.text for i in title])
    

    希望这会有所帮助!干杯!

    【讨论】:

      【解决方案2】:

      你可以使用 stripped_strings

      from bs4 import BeautifulSoup
      
      
      html = """<p class="attrgroup">
              <span><b>2013 Volkswagen Passat</b></span>
              <br>
            </p>
            <p class="attrgroup">
              <span>condition: <b>excellent</b></span>
              <br>
      </p>"""
      
      tag = BeautifulSoup(html, 'html.parser')
      
      data = (' '.join(tag.stripped_strings))
      print data
      

      【讨论】:

        猜你喜欢
        • 2019-06-03
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        • 2022-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多