用python的curl和lxml来抓取和分析网页内容

摘要:
Curl是一个强大的URL语法的客户端,支持DICT,FILE,FTP,FTPS,Gopher,HTTP,HTTPS,IMAP,IMAPS,LDAP,LDAPS,POP3,POP3S,RTMP,RTSP,SCP,SFTP,SMTP,SMTPS等多种协议。Lxml是python一个非常好用的xml模块,同时支持html的处理。虽然html是xml的一个子集,但是有些html网页写的不够标准,例如写了但是又没写,这种情况下使用xml工具来分析绝对是会报错的,但是html工具通常就可以很好的兼容这些非标准的情况。用urlparse的urljoin可以很好的帮你处理相对路径问题。如果你的python里面缺少了curl或者lxml等模块,可以到pypi去找。

Curl是一个强大的URL语法的客户端,支持DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS等多种协议。

Lxml是python一个非常好用的xml模块,同时支持html的处理。虽然html是xml的一个子集,但是有些html网页写的不够标准,例如写了<option>但是又没写</option>,这种情况下使用xml工具来分析绝对是会报错的,但是html工具通常就可以很好的兼容这些非标准的情况。

用urlparse的urljoin可以很好的帮你处理相对路径问题。

如果你的python里面缺少了curl或者lxml等模块,可以到pypi去找。

#!/usr/bin/env python#coding: utf-8

importos
importsys
importurlparse

importlxml.html
importlxml.etree
importcurl

defdownload(url):
    c =curl.Curl()
    c.set_timeout(8)
    c.get(url)
    returnc.body()

defparse_url():
    base_url = 'http://finance.ce.cn/stock/'ht_string =download(base_url)
    ht_doc =lxml.html.fromstring(ht_string, base_url)
    elms = ht_doc.xpath("//li[@style='font-size:15px; line-height:29px;']/a")
    for i inelms:
        print urlparse.urljoin(base_url, i.get('href'))
        print lxml.etree.tostring(i, encoding='utf-8')

if __name__ == '__main__':
    parse_url()

免责声明:文章转载自《用python的curl和lxml来抓取和分析网页内容》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇HTTP详解/一次HTTP过程Android应用的缓冲界面启动界面下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python 在不同层级目录import 模块的方法

有一个文件夹/home/a,  里面有个模块叫b.py,  我怎么把他import到程序里? 1). import sys; sys.path.append("/home/a/") import b 2). 在目录里面增加__init__.py文件,里面可以写import时执行的代码,当然也可以留空就可以. import home.a.b 3)....

curl实现SFTP上传下载文件

摘自:https://blog.csdn.net/swj9099/article/details/85292444 #include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <pthread.h...

Python和C++交互

关键字:Python 2.7,VS 2010,swig OS:Win8.1 with update。 1.下载swig:http://www.swig.org/download.html 2.将swig的路径添加到环境变量Path,例如set path=C:swigwin-3.0.2。 3.用VS创建一个win32 console application名...

How to install Ta-Lib in Python

Technical indicators are calculated using historical price and volume data to predict the market direction. These indicators are added on charts using which you can set your entry...

微信app支付,完整流程,完整代码 (转)

微信app支付流程 需要的配置参数 private function wechat($body,$indent_id,$cou,$user_id,$total_fee,$ip,$domain,$nonce_str){ //微信配置信息和初始逻辑 $appid= WxPayConfig::APPID; //appid (微信开放平台的应用appid) $bo...

python 装饰器语法糖(@classmethod @staticmethod @property @name.)原理剖析和运用场景

引用:http://blog.csdn.net/slvher/article/details/42497781 这篇文章系统的介绍这几者之间的关系和区别。有兴趣的朋友可以到上面的链接查看原文,这里我把原文拷贝如下(如有侵权,通知马上删除) ===========================================================...