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

yipeiwu_com6年前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

相关文章

浅谈python爬虫使用Selenium模拟浏览器行为

浅谈python爬虫使用Selenium模拟浏览器行为

前几天有位微信读者问我一个爬虫的问题,就是在爬去百度贴吧首页的热门动态下面的图片的时候,爬取的图片总是爬取不完整,比首页看到的少。原因他也大概分析了下,就是后面的图片是动态加载的。他的问...

在Python中使用cookielib和urllib2配合PyQuery抓取网页信息

在Python中使用cookielib和urllib2配合PyQuery抓取网页信息

刚才好无聊,突然想起来之前做一个课表的点子,于是百度了起来。 刚开始,我是这样想的:在写微信墙的时候,用到了urllib2【两行代码抓网页】,那么就只剩下解析html了。于是百度:pyt...

python爬取m3u8连接的视频

本文为大家分享了python爬取m3u8连接的视频方法,供大家参考,具体内容如下 要求:输入m3u8所在url,且ts视频与其在同一路径下 #!/usr/bin/env/pytho...

python爬虫中多线程的使用详解

queue介绍 queue是python的标准库,俗称队列.可以直接import引用,在python2.x中,模块名为Queue。python3直接queue即可 在python中,多个...

Python爬虫实现爬取京东手机页面的图片(实例代码)

实例如下所示: __author__ = 'Fred Zhao' import requests from bs4 import BeautifulSoup import os...