(美丽的汤)如何从HTML标签中提取数据

时间:2015-08-24 11:21:32

标签: python sqlite web-scraping beautifulsoup urllib2

到目前为止,我已经开始了。我无法从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中删除数据?我只需要文字和段落。
  2. 我需要在控制台中输出:

    RED I am paragraph red
    WHITE I am paragraph white
    PINK I am paragraph pink

    1. 如何自动将这些数据集导入SQL文件?
    2. 我想要的输出数据库表(名称,描述):

      name: RED,WHITE,PINK
      description: I am paragraph RED, I am paragraph WHITE, I am paragraph PINK
      

2 个答案:

答案 0 :(得分:1)

Answering question one, write it like this:

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

答案 1 :(得分:0)

试试这个解决方案:

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()