【问题标题】:(Beautiful Soup) How to extract data from HTML tags(美汤)如何从HTML标签中提取数据
【发布时间】:2015-11-17 19:18:56
【问题描述】:

到目前为止,我已经开始这样做了。我无法从 div 中获取正常文本。

from BeautifulSoup import BeautifulSoup
import urllib2
get = BeautifulSoup(urllib2.urlopen("https://example/com/").read()).findAll('div', {'class':'h4 entry-title'})
import sys
for  i in get:
print i

请问如何从这个 HTML 中删除数据?我只需要这些颜色名称和段落。

<div class="h4 entry-title">
<a href="https://example/com/01/">RED</a>
</div>
<p>
I am paragraph red
<p>

<div class="h4 entry-title">
<a href="https://example.com/02/">WHITE</a>
</div>
<p>
I am paragraph white
</p>


<div class="h4 entry-title">
<a href="https://example.com/03/">PINK</a>
</div>
<p>
I am paragraph pink
</p>

我的问题:

  1. 如何从这个 HTML 中删除数据?我只需要文本和段落。

我在控制台中需要的输出:

RED我是款红
WHITE我是款白
PINK我是款粉色
  1. 如何将这些数据集自动导入 SQL 文件?

我想要的输出数据库表(名称、描述):

名称:红色,白色,粉红色 描述:我是红色款,我是白色款,我是粉色款

【问题讨论】:

    标签: python sqlite web-scraping beautifulsoup urllib2


    【解决方案1】:

    回答问题一,这样写:

    for div in BeautifulSoup(urllib2.urlopen("https://example/com/").read()).findAll('div', {'class':'h4 entry-title'}):
        for a in div.findAll('a'):
            print a.text
        for p in div.findAll('p'):
            print p.text
    

    【讨论】:

      【解决方案2】:

      试试这个解决方案:

      from BeautifulSoup import BeautifulSoup
      import urllib2
      
      (...)
      connection = ...
      cursor = connection.cursor()
      (...)
      
      bs = BeautifulSoup(urllib2.urlopen("https://example/com/").read())
      
      names = []
      descriptions = []
      for title in bs.findAll('div', {'class': 'h4 entry-title'}):
          name = title.find('a').text
          description = title.find('p').text
          sdesc = description.split()
          sdesc[-1] = sdesc[-1].upper()
          names.append(name)
          descriptions.append(' '.join(sdesc))
          print name, description
      
      cursor.execute("INSERT INTO table (name, description) VALUES (%s, %s)", (','.join(names), ', '.join(descriptions))
      connection.commit()
      

      【讨论】:

      • 谢谢你!但我正在使用mysql。是否可以从此 python 代码自动转储到我的数据库中?我从来没有在mysql中使用过游标。看起来很有趣。寻找你的指导人!
      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2015-03-18
      • 2012-08-01
      • 2017-12-11
      相关资源
      最近更新 更多