欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例

程序员文章站 2022-05-07 16:05:49
熟悉java的jsoup包的话,对于python的beautifulsoup库应该很容易上手。 复制代码 代码如下:#coding: utf-8import sysimp...

熟悉java的jsoup包的话,对于python的beautifulsoup库应该很容易上手。

复制代码 代码如下:

#coding: utf-8
import sys
import urllib
import urllib2
from beautifulsoup import beautifulsoup

question_word = "吃货 程序员"
url = "http://www.baidu.com/s?wd=" + urllib.quote(question_word.decode(sys.stdin.encoding).encode('gbk'))
htmlpage = urllib2.urlopen(url).read()
soup = beautifulsoup(htmlpage)
print len(soup.findall("table", {"class": "result"}))
for result_table in soup.findall("table", {"class": "result"}):
    a_click = result_table.find("a")
    print "-----标题----\n" + a_click.rendercontents()#标题
    print "----链接----\n" + str(a_click.get("href"))#链接
    print "----描述----\n" + result_table.find("div", {"class": "c-abstract"}).rendercontents()#描述
    print