Open eziceice opened 6 years ago
XHTML是HTML最新的方言, 是XML的一种形式. 由于浏览器可以宽容的接受许多种类的html错误并且尽可能的对其进行解析, 导致网络上许多的html网页的格式有很多问题, 这对于屏幕抓取是非常不方便的.
XHTML和HTML的主要区别有两个, 首先XHTML对于显示关闭所有元素要求更加严格, 必须使用开始和关闭tag才能关闭一段元素. 这种行为让XHTML变得非常容易解析, 因为可以直接告诉程序什么时候进入或离开各种元素. 另外一个区别就是XHTML是XML的一种, 所以可以对他使用XML工具, 比如XPATH.
Tidy是用来修复不规范且有些随意的html文档的工具. 它能够以相当智能的方法修复一般的错误, 做那些你不愿意做的事情. 它也是可设置的, 也可以打开或者关闭各种修改选项.
使用HTMLParser(Python标准库)可以处理XHTML. 当使用XHTML时, 需要生成一个它的子类, 并且对handle_starttag和handle_data之类的事件处理方法进行override.
from urllib import request
from html.parser import HTMLParser
class Scraper(HTMLParser): in_h3 = False in_link = False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == 'h3':
self.in_h3 = True
if tag == 'a' and 'herf' in attrs:
self.in_link = True
self.chunks = []
self.url = attrs['href']
def handle_data(self, data):
if self.in_link:
self.chunks.append(data)
def handle_endtag(self, tag):
if tag == 'h3':
self.in_h3 = False
if tag == 'a':
if self.in_h3 and self.in_link:
print(self.chunks, self.url)
self.in_link = False
text = request.urlopen('https://www.google.com').read() text = bytes.decode(text) parser = Scraper() parser.feed(text) #解析HTML parser.close()
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
...
"""
from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser') print(soup.title) print(soup.head) print(soup.title.string) print(soup.find_all('a'))
CGI(Common Gateway Interface)通用网关接口,是网络服务器可以将查询(一般来说是web表单)传递到专门的程序中并且在网页上显示结果的标准机制. 它是创建web应用程序的一种简便的方法, 无需编写特殊的应用服务器.
Python CGI程序设计的关键工具是cgi模块, cgitb是另外一个在CGI脚本开发过程中的有用的模块. 使用CGI脚本可通过网络访问(运行)之前, 需要将它们放到网络服务器可以访问的地方, 并且加入pound bang行, 设置合适的文件权限.
Step 1: 准备网络服务器, 一般来说就是把需要的文件放置在网络上. CGI程序也必须放在通过网络可以访问的目录中, 并且必须将他们标识为CGI脚本. 这样网络服务器就不会将普通的源代码作为网页处理. 有两个方法可以实现这个功能:
将脚本放在叫做cgi-bin的子目录中
把脚本文件扩展名改为.cgi
Step 2: 加入Pound Bang行, 当把脚本放在正确位置后, 需要在脚本的开始处增加pound bang行. 通常来说, 只要把下面这行加到脚本开始处就可以了: 注意, 它一定要是第一行. 如果不能正常工作, 需要查看Python可执行文件的确切位置.
#!/usr/bin/env python‘
- Step 3: 设置文件权限, 最后一件事是设置合适的文件权限.要确保每个人都可以读取和执行脚本文件, 但是还要确保只有你可以写入. 修改文件权限的UNIX命令是chmod. 只要运行以下的命令即可(如果脚本叫做somescript.cgi), 使用普通的用户账户, 或者为这类Web任务特别建立的账户: 在做好所有这些准备后, 应该能将脚本作为网页打开并且执行.
chmod 755 somescript.cgi
- 一般来说不允许CGI脚本修改计算机上的任何文件. 如果想要它修改文件, 必须显式地给它设置相应的权限. 这时有两个选项, 如果有root(系统管理员)权限的话, 那么可以为你的脚本创建一个用户账户, 改变需要修改的文件的所有权. 如果没有root权限, 则可以为文件设置文件权限, 这样系统上的所有用户(包括网络服务器用来运行CGI脚本的用户)都被允许写文件.
chmod 666 editable_file.txt #使用666可能会导致潜在危险
Web服务一般应用于很高层次的抽象, 它使用HTTP(Web协议)作为底层协议, 上面则是更多面向内容的协议. 比如WSDL, 是一种描述通过服务可获得何种方法以及方法的参数和返回值等内容的XML格式的语言.
RSS代表富站点摘要(Rich Site Summary), RDF站点摘要或简易信息聚合(Really Simple Syndication), 是在XML中列出新闻项目的最简单的格式. RSS文档(或称feed)更像服务而不是静态文档的原因是它们是定期更新的, 甚至可以对它们执行动态计算.
如今常用的Web服务: XML-RPC, 可以看做是使用简单的XML在系统之间通信, 现在已经不常用了. REST, 使用JSON在系统之间通信, 效率很高非常优雅, 但安全性一般. SOAP, 使用标准化格式的XML在系统之间通信, 比较庞大, 但是安全性较高.
屏幕抓取