python爬取网页数据步骤图解,如何利用python爬取网页内容

  python爬取网页数据步骤图解,如何利用python爬取网页内容

  

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

  导入webbrowser

  webbrowser . open( http://I . Firefox China.cn/?from=world index’)

  True:用脚本打开网页。

  所有Python程序的第一行都应该以#开头!在python的开头,它告诉计算机,它希望Python执行这个程序。(我没有尝试过这一行,还行,也许是一种常态。)

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

  2.读取剪贴板内容:

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

  #!python3

  importwebbrowser,sys,pyperclip

  iflen(系统argv)1:

  mapAddress=“”。join(sys.argv[1:])

  else:

  mapAddress=pyperclip.paste()

  webbrowser . open( http://map . Baidu.com/?map=1ie=utf-8s=s & amp;wd= mapaddress注:如果不知道sys.argv的用法,请参考这里;如果你不知道的用法。join(),请参考这里。Sys.argv是一个字符串列表,因此将其传递给join()方法会返回一个字符串。

  好,现在选择单词‘天安门广场’并复制它,然后双击你桌面上的程序。当然,你也可以在命令行找到你的程序,输入位置。

  相关:《Python教程》

  二、用requests模块从Web下载文件:

  Python中不包含请求模块。从命令行运行pip安装请求。不翻墙很难安装成功。请参考这里的手动安装。

  导入请求

  RES=requests . get( http://I . Firefox China.cn/?From=worldindex)#传入要获取的URL

  Type(res)#响应对象

  类“requests.models.Response”

  Print(res.status_code)#响应代码

  200

  在res.text#返回的文本请求中,有多种方式可以查看从互联网下载的文件内容。如果在以后的博客中用到,会有说明,这里就不一一介绍了。在下载文件的过程中,raise_for_status()方法可以保证下载真的成功,然后让程序继续做其他的事情。

  导入请求

  RES=requests . get( http://I . Firefox China.cn/?from=world index’)

  尝试:

  res.raise_for_status()

  exceptExceptionasexc:

  打印( thewasaproblem :% s %(exc))三、将下载的文件保存到本地:

  顽童

  ortrequests

  >>>res=requests.get('http://tech.firefox.sina.com/17/0820/10/6DKQALVRW5JHGE1I.html##0-tsina-1-13074-

  397232819ff9a4

  7a7b7e80a40613cfe1')

  >>>res.raise_for_status()

  >>>file=open('1.txt','wb')#以写二进制模式打开文件,目的是保存文本中的“Unicode编码”

  >>>forwordinres.iter_content(100000):#<spanclass="fontstyle0"><spanclass="fontstyle0">iter_content()

  </span>

  <spanclass="fontstyle1">方法在循环的每次迭代中返回一段</span><spanclass="fontstyle0">bytes</span><spanclass=

  "fontstyle1">数据</span><spanclass="fontstyle1">类型的内容,你需要指定其包含的字节数</span></span>

  file.write(word)

  

  16997

  >>>file.close()四、用BeautifulSoup模块解析HTML:在命令行中用pip install beautifulsoup4安装它。

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

  

>>>importrequests,bs4

  >>>res=requests.get('http://i.firefoxchina.cn/?from=worldindex')

  >>>res.raise_for_status()

  >>>soup=bs4.BeautifulSoup(res.text)

  

  Warning(fromwarningsmodule):

  File"C:\Users\King\AppData\Local\Programs\Python\Python36-32\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg

  \bs4\__init__.py",line181

  markup_type=markup_type))

  UserWarning:Noparserwasexplicitlyspecified,soI'musingthebestavailableHTMLparserforthis

  system

  ("html.parser").Thisusuallyisn'taproblem,butifyourunthiscodeonanothersystem,orina

  differentvirtual

  environment,itmayuseadifferentparserandbehavedifferently.

  

  Thecodethatcausedthiswarningisonline1ofthefile<string>.Togetridofthiswarning,

  changecodethat

  lookslikethis:

  BeautifulSoup(YOUR_MARKUP})

  tothis:

  BeautifulSoup(YOUR_MARKUP,"html.parser")

  

  >>>soup=bs4.BeautifulSoup(res.text,'html.parser')

  >>>type(soup)

  <class'bs4.BeautifulSoup'>

我这里有错误提示,所以加了第二个参数。

  

>>>importbs4

  >>>html=open('C:\\Users\\King\\Desktop\\1.htm')

  >>>exampleSoup=bs4.BeautifulSoup(html)

  >>>exampleSoup=bs4.BeautifulSoup(html,'html.parser')

  >>>type(exampleSoup)

  <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的元素。

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

  

>>>importrequests,bs4

  >>>res=requests.get('http://i.firefoxchina.cn/?from=worldindex')

  >>>res.raise_for_status()

  >>>soup=bs4.BeautifulSoup(res.text,'html.parser')

  >>>author=soup.select('#author')

  >>>print(author)

  []

  >>>type(author)

  <class'list'>

  >>>link=soup.select('link')

  >>>print(link)

  [<linkhref="css/mozMainStyle-min.css?v=20170705"rel="externalnofollow"rel="externalnofollow"rel="

  stylesheet"

  type="text/css"/>,<linkhref=""id="rel="externalnofollow"rel="externalnofollow"rel="external

  nofollow"

  moz-skin"rel="stylesheet"type="text/css"/>,<linkhref=""id="rel="externalnofollow"rel="external

  nofollow"

  rel="externalnofollow"moz-dir"rel="stylesheet"type="text/css"/>,<linkhref=""id="rel="external

  nofollow"

  rel="externalnofollow"rel="externalnofollow"moz-ver"rel="stylesheet"type="text/css"/>]

  >>>type(link)

  <class'list'>

  >>>len(link)

  4

  >>>type(link[0])

  <class'bs4.element.Tag'>

  >>>link[0]

  <linkhref="css/mozMainStyle-min.css?v=20170705"rel="externalnofollow"rel="externalnofollow"rel="stylesheet"

  type="text/css"/>

  >>>link[0].attrs

  {'rel':['stylesheet'],'type':'text/css','href':'css/mozMainStyle-min.css?v=20170705'}

3.通过元素的属性获取数据:接着上面的代码写。

  

>>>link[0].get('href')

  'css/mozMainStyle-min.css?v=20170705

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: