rainit2006 / Python-room

my python room
0 stars 0 forks source link

爬虫 #12

Open rainit2006 opened 6 years ago

rainit2006 commented 6 years ago

rainit2006 commented 6 years ago

教程和实例

rainit2006 commented 6 years ago

常用库文件

RegexPal : 在线测试正则表达式。 http://regexpal.com/

rainit2006 commented 5 years ago

计划: 1,代码运行成功真正的一个数据提取和图形显示的例子 2, 实际应用到丁的网站上试试效果

rainit2006 commented 5 years ago

-书籍 《Web Scraping with Python: Collecting Data from the Modern Web 》

rainit2006 commented 5 years ago

Beautiful Soup https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

■Beautiful Soup解析器(Parser)比较 用法:

BeautifulSoup(markup, "lxml")
BeautifulSoup(markup, "html.parser")

比较: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser lxml parser is generally faster, html5lib is the most lenient one - this kind of difference would be relevant if you have a broken or non-well-formed HTML to parse. html.parser is built-in and can help to avoid extra dependencies, if this is a problem.

■findAll函数 findAll(tag, attributes, recursive, text, limit, keywords) find(tag, attributes, recursive, text, keywords)

nameList = bsObj.findAll("span", {"class":"green"})
for name in nameList:
    print(name.get_text())

Tag代表要检索的标签。下面的代码将返回一个包含 HTML 文档中所有标题标签的列表: .findAll({"h1","h2","h3","h4","h5","h6"}) 属性参数 attributes 是用一个 Python 字典封装一个标签的若干属性和对应的属性值。例如,下面这个函数会返回 HTML 文档里红色与绿色两种颜色的 span 标签: .findAll("span", {"class":{"green", "red"}}) 递归参数 recursive 是一个布尔变量。你想抓取 HTML 文档标签结构里多少层的信息?如果 recursive 设置为 True ,findAll 就会根据你的要求去查找标签参数的所有子标签,以及子标签的子标签。如果 recursive 设置为 False ,findAll 就只查找文档的一级标签。findAll 默认是支持递归查找的(recursive 默认值是 True )

文本参数 text 有点不同,它是用标签的文本内容去匹配,而不是用标签的属性。假如我们想查找前面网页中包含“the prince”内容的标签数量,我们可以把之前的 findAll 方法换成下面的代码: nameList = bsObj.findAll(text="the prince") print(len(nameList))

范围限制参数 limit ,显然只用于 findAll 方法。find 其实等价于 findAll 的 limit 等于 1 时的情形。如果你只对网页中获取的前 x 项结果感兴趣,就可以设置它。但是要注意,这个参数设置之后,获得的前几项结果是按照网页上的顺序排序的,未必是你想要的那前几项。

还有一个关键词参数 keyword ,可以让你选择那些具有指定属性的标签。例如: allText = bsObj.findAll(id="text") print(allText[0].get_text()) 下面两行代码是完全一样的: bsObj.findAll(id="text") bsObj.findAll("", {"id":"text"})

■处理子标签和其他后代标签(Dealing with children and other descendants) 在 BeautifulSoup 库里,孩子 (child)和后代 (descendant)有显著的不同:和人类的家谱一样,子标签就是一个父标签的下一级,而后代标签是指一个父标签下面所有级别的标签。例如,tr 标签是 table 标签的子标签,而 tr 、th 、td 、img 和 span 标签都是 table 标签的后代标签(我们的示例页面中就是如此)。所有的子标签都是后代标签,但不是所有的后代标签都是子标签。

如果你只想找出子标签,可以用 .children 标签:

for child in bsObj.find("table",{"id":"giftList"}).children:
    print(child)

■处理兄弟标签 previous_sibling 和 next_siblings() 函数

for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
    print(sibling)

■父标签处理 parent 和 parents

print(bsObj.find("img",{"src":"../img/gifts/img1.jpg"
                       }).parent.previous_sibling.get_text())

■获取属性 对于一个标签对象,可以用下面的代码获取它的全部属性: myTag.attrs 要获取图片的资源位置 src ,可以用下面这行代码: myImgTag.attrs["src"]

利用lamda式子,获取有两个属性的标签: soup.findAll(lambda tag: len(tag.attrs) == 2)

■get_text()函数 get_text() 会把你正在处理的 HTML 文档中所有的标签都清除,然后返回一个只包含文字的字符串。假如你正在处理一个包含许多超链接、段落和标签的大段源代码,那么 .get_text() 会把这些超链接、段落和标签都清除掉,只剩下一串不带标签的文字。

rainit2006 commented 5 years ago

正则表达式 邮箱地址的正则表达式 [A-Za-z0-9._+]+@[A-Za-z]+.(com|org|edu|net)

常用正则表达式爬取网页信息及分析HTML标签总结 https://blog.csdn.net/Eastmount/article/details/51082253 获取超链接之间内容

   res = r'<a .*?>(.*?)</a>'

■ 贪婪匹配 在满足匹配时,匹配尽可能长的字符串,默认情况下,采用贪婪匹配

string pattern1 = @"a.*c";
   // greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); //
 return "abcabc"

■ 非贪婪匹配:利用?号 在满足匹配时,匹配尽可能短的字符串,使用?来表示非贪婪匹配

string pattern1 = @"a.*?c";
   // non-greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); //
 return "abc"

几个常用的非贪婪匹配Pattern

*? 重复任意次,但尽可能少重复
+? 重复1次或更多次,但尽可能少重复
?? 重复0次或1次,但尽可能少重复
{n,m}? 重复n到m次,但尽可能少重复
{n,}? 重复n次以上,但尽可能少重复
rainit2006 commented 5 years ago

■常用处理: 取得页面所有链接的href和text内容

html = urlopen('http://xxxxxxxx')
bs = BeautifulSoup(html, "html.parser")
for a in bs.body.findAll('a', href=True):
    print("Found the URL:", a['href'])
    print("URL text:", a.text)

■关于Tag和NavigableString 例子:

Tag 是<a><br>等标签,比如:
<a href="https://flic.kr/p/JjGqdx" target="_blank">12分充電後メーター</a>
<br/>
NavigableString  是文字,比如:51%→70%, 131㎞→180㎞

判断方法(isinstance):

from bs4 import BeautifulSoup, NavigableString, Tag
....
for item in node.next_siblings:
    if isinstance(item, NavigableString):
        print("NavigableString %s" % item)
    if isinstance(item, Tag):
        print("Tag %s" % item)
rainit2006 commented 5 years ago

Scrapy框架