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

yipeiwu_com5年前Python爬虫

熟悉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

相关文章

python2使用bs4爬取腾讯社招过程解析

目的:获取腾讯社招这个页面的职位名称及超链接 职位类别 人数 地点和发布时间 要求:使用bs4进行解析,并把结果以json文件形式存储 注意:如果直接把python列表没有序列化为jso...

python爬虫 urllib模块发起post请求过程解析

python爬虫 urllib模块发起post请求过程解析

urllib模块发起的POST请求 案例:爬取百度翻译的翻译结果 1.通过浏览器捉包工具,找到POST请求的url 针对ajax页面请求的所对应url获取,需要用到浏览器的捉包工具。...

python爬虫的数据库连接问题【推荐】

python爬虫的数据库连接问题【推荐】

1.需要导的包 import pymysql 2.# mysql连接信息(字典形式) db_config ={ 'host': '127.0.0.1',#连接的主机id(107.0...

Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】

本文实例讲述了Python HTML解析器BeautifulSoup用法。分享给大家供大家参考,具体如下: BeautifulSoup简介 我们知道,Python拥有出色的内置HTML解...

python抓取网页时字符集转换问题处理方案分享

问题提出:     有时候我们采集网页,处理完毕后将字符串保存到文件或者写入数据库,这时候需要制定字符串的编码,如果采集网页的编码是gb2312,而我们的数...