网页抓取方式(六)--python/urllib3/BeautifulSoup
来源:互联网 发布:淘宝富光保温杯 编辑:程序博客网 时间:2024/06/08 13:51
一、简介
本文介绍使用python语言进行网页抓取的方法。在此使用urllib3(urllib2也可以的,但容易被查封)进行网页抓取,
使用BeautifulSoup对抓取的网页进行解析。
二、注意
1、使用BeautifulSoup对html解析时,当使用css选择器,对于子元素选择时,要将nth-child改写为nth-of-type才行,
如 ul:nth-child(1) 应该写为 ul:nth-of-type(1) ,否则会报错Only the following pseudo-classes are implemented: nth-of-type.
二、实例代码
#! /usr/bin/evn pythonfrom bs4 import BeautifulSoupimport urllib3def get_html(url): try: userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6' http = urllib3.PoolManager(timeout=2) response = http.request('get', url, headers={'User_Agent': userAgent}) html = response.data return html except Exception, e: print e return Nonedef get_soup(url): if not url: return None try: soup = BeautifulSoup(get_html(url)) except Exception, e: print e return None return soupdef get_ele(soup, selector): try: ele = soup.select(selector) return ele except Exception, e: print e return Nonedef main(): url = 'http://www.ifeng.com/' soup = get_soup(url) ele = get_ele(soup, '#headLineDefault > ul > ul:nth-of-type(1) > li.topNews > h1 > a') headline = ele[0].text.strip() print headlineif __name__ == '__main__': main()
阅读全文
0 0
- 网页抓取方式(六)--python/urllib3/BeautifulSoup
- python 抓取网页--用BeautifulSoup
- Python爬虫包 BeautifulSoup 学习(六) 递归抓取
- python beautifulsoup多线程分析抓取网页
- BeautifulSoup+正则+Python 抓取网页数据
- python beautifulsoup 抓取网页正文内容
- python beautifulsoup多线程分析抓取网页
- python : BeautifulSoup 网页 table 抓取实例
- 【Python网络爬虫】Python维基百科网页抓取(BeautifulSoup+Urllib2)
- Python抓取网页&批量下载文件方法初探(正则表达式+BeautifulSoup)
- Python抓取网页&批量下载文件方法初探(正则表达式+BeautifulSoup)
- 使用Python+selenium+BeautifulSoup抓取动态网页的关键信息
- python爬虫,抓取新浪科技的文章(beautifulsoup+mysql)
- 运用BeautifulSoup抓取网页的链接
- 运用BeautifulSoup抓取网页的链接
- Python之BeautifulSoup学习之一 粗略抓取网页图片连接地址
- python爬虫系列(六):强大的beautifulsoup
- Python结合BeautifulSoup抓取知乎数据
- 理解原型链
- coinhive是什么?
- [agc019e]Shuffle and Swap
- 关于同一服务器配置多个tomcat的问题
- Servlet (三 Response 对象)
- 网页抓取方式(六)--python/urllib3/BeautifulSoup
- 数据结构:散列
- 简单 的 js 投票页面
- 字符集,代码页,字符编码
- 1.MariaDB笔记——MaraDB的Linux安装
- 在数组中找到次数大于N/K的数
- 大白菜系统重装步骤
- 数据结构:红黑树
- k阶斐波那契数列的c语言程序