Python学习(从Web抓取信息)

来源:互联网 发布:windows安装盘 编辑:程序博客网 时间:2024/05/01 07:28

一、利用webbrowser.open()打开一个网站:

[python] view plain copy
  1. >>> import webbrowser  
  2. >>> webbrowser.open('http://i.firefoxchina.cn/?from=worldindex')  
  3. True  

实例:使用脚本打开一个网页。

所有Python程序的第一行都应以#!python开头,它告诉计算机想让Python来执行这个程序。(我没带这行试了试,也可以,可能这是一种规范吧)

1.sys.argv读取命令行参数:打开一个新的文件编辑器窗口,输入下面的代码,将其保存为map.py

2.读取剪贴板内容:

3.调用webbrowser.open()函数打开外部浏览:

[python] view plain copy
  1. #! python3  
  2. import webbrowser, sys, pyperclip  
  3. if len(sys.argv) > 1:  
  4.     mapAddress = ''.join(sys.argv[1:])  
  5. else:  
  6.     mapAddress = pyperclip.paste()  
  7. webbrowser.open('http://map.baidu.com/?newmap=1&ie=utf-8&s=s%26wd%3D' + mapAddress  

注:不清楚sys.argv用法的,请参考这里;不清楚.join()用法的,请参考这里。sys.argv是字符串的列表,所以将它传递给join()方法返回一个字符串

好了,现在选中'天安门广场'这几个字并复制,然后到桌面双击你的程序。当然你也可以在命令行找到你的程序,然后输入地点。

二、用requests模块从Web下载文件requests模块不是Python自带的,通过命令行运行pip install request安装。没翻墙是很难安装成功的,手动安装可以参考这里。

[python] view plain copy
  1. >>> import requests  
  2. >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex')    #向get中传入一个网址  
  3. >>> type(res)    #响应对象  
  4. <class 'requests.models.Response'>  
  5. >>> print(res.status_code)    #响应码  
  6. 200  
  7. >>> res.text    #返回的文本  
requests中查看网上下载的文件内容的方法还有很多,如果以后的博客用的到,会做说明,在此不再一一介绍。在下载文件的过程中,用raise_for_status()方法可以确保下载确实成功,然后再让程序继续做其他事情。 

[python] view plain copy
  1. import requests  
  2. res = requests.get('http://i.firefoxchina.cn/?from=worldindex')  
  3. try:  
  4.     res.raise_for_status()  
  5. except Exception as exc:  
  6.     print('There was a problem: %s' % (exc))  
三、将下载的文件保存到本地

[python] view plain copy
  1. >>> import requests  
  2. >>> res = requests.get('http://tech.firefox.sina.com/17/0820/10/6DKQALVRW5JHGE1I.html##0-tsina-1-13074-397232819ff9a47a7b7e80a40613cfe1')  
  3. >>> res.raise_for_status()  
  4. >>> file = open('1.txt''wb')    #以写二进制模式打开文件,目的是保存文本中的“Unicode编码”  
  5. >>> for word in res.iter_content(100000):    #<span class="fontstyle0"><span class="fontstyle0">iter_content()</span><span class="fontstyle1">方法在循环的每次迭代中返回一段</span><span class="fontstyle0">bytes</span><span class="fontstyle1">数据</span><span class="fontstyle1">类型的内容,你需要指定其包含的字节数</span></span>  
  6.     file.write(word)  
  7.   
  8.       
  9. 16997  
  10. >>> file.close()  
四、用BeautifulSoup模块解析HTML在命令行中用pip install beautifulsoup4安装它。

1.bs4.BeautifulSoup()函数可以解析HTML网站链接requests.get(),也可以解析本地保存的HTML文件,直接open()一个本地HTML页面

[python] view plain copy
  1. >>> import requests, bs4  
  2. >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex')  
  3. >>> res.raise_for_status()  
  4. >>> soup = bs4.BeautifulSoup(res.text)  
  5.   
  6. Warning (from warnings module):  
  7.   File "C:\Users\King\AppData\Local\Programs\Python\Python36-32\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg\bs4\__init__.py", line 181  
  8.     markup_type=markup_type))  
  9. UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.  
  10.   
  11. The code that caused this warning is on line 1 of the file <string>. To get rid of this warning, change code that looks like this:  
  12.   
  13.  BeautifulSoup(YOUR_MARKUP})  
  14.   
  15. to this:  
  16.   
  17.  BeautifulSoup(YOUR_MARKUP, "html.parser")  
  18.   
  19. >>> soup = bs4.BeautifulSoup(res.text, 'html.parser')  
  20. >>> type(soup)  
  21. <class 'bs4.BeautifulSoup'>  
我这里有错误提示,所以加了第二个参数。

[python] view plain copy
  1. >>> import bs4  
  2. >>> html = open('C:\\Users\\King\\Desktop\\1.htm')  
  3. >>> exampleSoup = bs4.BeautifulSoup(html)  
  4. >>> exampleSoup = bs4.BeautifulSoup(html, 'html.parser')  
  5. >>> type(exampleSoup)  
  6. <class 'bs4.BeautifulSoup'>  
2.用select()方法寻找元素:需传入一个字符串作为CSS“选择器”来取得Web页面相应元素,例如:

soup.select('div'):所有名为<div>的元素;

soup.select('#author'):带有id属性为author的元素;

soup.select('.notice'):所有使用CSS class属性名为notice的元素;

soup.select('div span'):所有在<div>元素之内的<span>元素;

soup.select('input[name]'):所有名为<input>并有一个name属性,其值无所谓的元素;

soup.select('input[type="button"]'):所有名为<input>并有一个type属性,其值为button的元素。

想查看更多的解析器,请参看这里。

[python] view plain copy
  1. >>> import requests, bs4  
  2. >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex')  
  3. >>> res.raise_for_status()  
  4. >>> soup = bs4.BeautifulSoup(res.text, 'html.parser')  
  5. >>> author = soup.select('#author')  
  6. >>> print(author)  
  7. []  
  8. >>> type(author)  
  9. <class 'list'>  
  10. >>> link = soup.select('link ')  
  11. >>> print(link)  
  12. [<link href="css/mozMainStyle-min.css?v=20170705" rel="stylesheet" type="text/css"/>, <link href="" id="moz-skin" rel="stylesheet" type="text/css"/>, <link href="" id="moz-dir" rel="stylesheet" type="text/css"/>, <link href="" id="moz-ver" rel="stylesheet" type="text/css"/>]  
  13. >>> type(link)  
  14. <class 'list'>  
  15. >>> len(link)  
  16. 4  
  17. >>> type(link[0])  
  18. <class 'bs4.element.Tag'>  
  19. >>> link[0]  
  20. <link href="css/mozMainStyle-min.css?v=20170705" rel="stylesheet" type="text/css"/>  
  21. >>> link[0].attrs  
  22. {'rel': ['stylesheet'], 'type''text/css''href''css/mozMainStyle-min.css?v=20170705'}  
3.通过元素的属性获取数据:接着上面的代码写。

[python] view plain copy
  1. >>> link[0].get('href')  
  2. 'css/mozMainStyle-min.css?v=20170705  
上面这些方法也算是对“网络爬虫”的一些初探。
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 闺蜜给介绍对象怎么办 喜欢对象的发小怎么办 山东省直医保卡丢失怎么办 高铁票如果错过了怎么办 动车错过了时间怎么办 长途动车错过了怎么办 动车如果错过了怎么办 没有取票错过了怎么办 动车出站没检票怎么办 火车晚点耽误了下班车怎么办 动车票中途丢了怎么办 购买二手房异地铁路公积金怎么办 沈阳公积金卡丢了怎么办 住宅专项维修资金用完了怎么办 广州出租车丢了东西怎么办 广州的士丢了东西怎么办 网上找兼职被骗了怎么办 海信空调开不了机怎么办 海信空调遥控器开不了怎么办 学生遭套路贷反被仲裁怎么办 赏脸打错字尝脸怎么办 红掌的花变黑了怎么办 红掌花苞发黑了怎么办 水培植物腐根了怎么办 水培绿萝水发臭怎么办 水里养花根烂掉怎么办 桅子花叶子发黑怎么办 大株月季烂根怎么办 月季水浇多了烂根的怎么办 金桔盆栽烂根怎么办 盆栽的长寿果树烂根怎么办 家里的石榴烂根怎么办 山桔盆栽烂根怎么办 养的植物烂根怎么办 桅子花叶子长霉怎么办 紫薇花叶子干了怎么办 高层玻璃阳台往下看恐高怎么办 比熊放阳台叫怎么办 海员入职体检不合格怎么办 联币金融立案投资人怎么办 联币金融的投资怎么办