本文摘自php中文网,作者(*-*)浩,侵删。
Python用做数据处理还是相当不错的,如果你想要做爬虫,Python是很好的选择,它有很多已经写好的类包,只要调用,即可完成很多复杂的功能。
1 Pyhton获取网页的内容(也就是源代码)(推荐学习:Python视频教程)
1 2 3 4 | page = urllib2.urlopen(url)
contents = page.read()
#获得了整个网页的内容也就是源代码
print (contents)
|
url代表网址,contents代表网址所对应的源代码,urllib2是需要用到的包,以上三句代码就能获得网页的整个源代码
2 获取网页中想要的内容(先要获得网页源代码,再分析网页源代码,找所对应的标签,然后提取出标签中的内容)
以豆瓣电影排名为例子
现在我需要获得当前页面的所有电影的名字,评分,评价人数,链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #coding:utf-8
'' '' '
@author: jsjxy
'' '
import urllib2
import re
from bs4 import BeautifulSoup
from distutils.filelist import findall
page = urllib2.urlopen( 'http://movie.douban.com/top250?format=text' )
contents = page.read()
# print (contents)
soup = BeautifulSoup(contents, "html.parser" )
print ( "豆瓣电影TOP250" + "\n" + " 影片名 评分 评价人数 链接 " )
for tag in soup.find_all( 'div' , class_= 'info' ):
# print tag
m_name = tag.find( 'span' , class_= 'title' ).get_text()
m_rating_score = float(tag.find( 'span' ,class_= 'rating_num' ).get_text())
m_people = tag.find( 'div' ,class_= "star" )
m_span = m_people.findAll( 'span' )
m_peoplecount = m_span[3].contents[0]
m_url=tag.find( 'a' ).get( 'href' )
print ( m_name+ " " + str(m_rating_score) + " " + m_peoplecount + " " + m_url )
|
控制台输出,你也可以写入文件中
更多Python相关技术文章,请访问Python教程栏目进行学习!
以上就是python 怎么获取网页内容的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
bool函数怎么用?
安装完Python怎么打开
Python中tornado的路由解析(附实例)
sublime怎么写Python程序
Python后端是什么
Python--堡垒机的介绍
Python单链表中如何查找和删除节点?
Python爬虫爬图片需要什么
Python中hashlib加密模块的分析(代码实例)
Python数据分析怎么学
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python 怎么获取网页内容