使用Python脚本获取标题标签的内容

Cos*_*smo 2 html python mysql sql

我想在Python中制作一个真正的脚本,它从指定网页的标题标签中获取内容,然后将它们放入MySQL数据库中.

我对Python的经验很少(而且我的意思是非常),但这需要为我的项目完成.我怎样才能以最简单的方式做到这一点?

我希望你能理解我想问的问题.

unu*_*tbu 5

  1. 研究urllib2,看看如何下载网页.
  2. 研究BeautifulSoup来解析HTML并提取标题.
  3. 研究Python数据库API规范以将行插入MySQL数据库.

以下是一些示例代码,可帮助您入门:

import urllib2
import BeautifulSoup
import MySQLdb

f = urllib2.urlopen('http://www.python.org/')
soup=BeautifulSoup.BeautifulSoup(f.read())
title=soup.find('title')
print(title.string)

connection=MySQLdb.connect(
    host='HOST',user='USER',
    passwd='PASS',db='MYDB')
cursor=connection.cursor()

sql='''CREATE TABLE IF NOT EXISTS foo (
           fooid int(11) NOT NULL AUTO_INCREMENT,
           title varchar(100) NOT NULL,
           PRIMARY KEY (fooid)
       )'''
cursor.execute(sql)

sql='INSERT INTO foo (title) VALUES (%s)'
args=[title.string]
cursor.execute(sql,args)
cursor.close()
connection.close()
Run Code Online (Sandbox Code Playgroud)