python獲取子節點
1. python xpath 判斷是否有某個子節點
一個簡單的例子,取myxml的第一個節點的值 from xml.dom.minidom import parse, parseStringdom1 = parseString('Some data some more data')print(dom1.getElementsByTagName("myxml")[0].childNodes[0].data)
2. python里利用bs4如何依次訪問源代碼的子節點
123456789def get_number_with_2child(self): if self.left and self.right: return 1+self.left.get_number_with_2child()+self.right.get_number_with_2child() elif self.left: return self.left.get_number_with_2child() elif self.rught: return self.right.get_number_with_2child() else: return 0
3. Python爬蟲:想聽榜單歌曲只需要14行代碼即可搞定
雖然說XPath比正則表達式用起來方便,但是沒有最方便,只有更方便。我們的BeautifulSoup庫就能做到更方便的爬取想要的東西。
使用之前,還是老規矩,先安裝BeautifulSoup庫,指令如下:
其中文開發文檔:
BeautifulSoup庫是一個強大的Python語言的XML和HTML解析庫。它提供了一些簡單的函數來處理導航、搜索、修改分析樹等功能。
BeautifulSoup庫還能自動將輸入的文檔轉換為Unicode編碼,輸出文檔轉換為UTF-8編碼。
所以,在使用BeautifulSoup庫的過程中,不需要開發中考慮編碼的問題,除非你解析的文檔,本身就沒有指定編碼方式,這才需要開發中進行編碼處理。
下面,我們來詳細介紹BeautifulSoup庫的使用規則。
下面,我們來詳細介紹BeautifulSoup庫的重點知識。
首先,BeautifulSoup庫中一個重要的概念就是選擇解釋器。因為其底層依賴的全是這些解釋器,我們有必要認識一下。博主專門列出了一個表格:
從上面表格觀察,我們一般爬蟲使用lxml HTML解析器即可,不僅速度快,而且兼容性強大,只是需要安裝C語言庫這一個缺點(不能叫缺點,應該叫麻煩)。
要使用BeautifulSoup庫,需要和其他庫一樣進行導入,但你雖然安裝的是beautifulsoup4,但導入的名稱並不是beautifulsoup4,而是bs4。用法如下:
運行之後,輸出文本如下:
基礎的用法很簡單,這里不在贅述。從現在開始,我們來詳細學習BeautifulSoup庫的所有重要知識點,第一個就是節點選擇器。
所謂節點選擇器,就是直接通過節點的名稱選擇節點,然後再用string屬性就可以得到節點內的文本,這種方式獲取最快。
比如,基礎用法中,我們使用h1直接獲取了h1節點,然後通過h1.string即可得到它的文本。但這種用法有一個明顯的缺點,就是層次復雜不適合。
所以,我們在使用節點選擇器之前,需要將文檔縮小。比如一個文檔很多很大,但我們獲取的內容只在id為blog的p中,那麼我們先獲取這個p,再在p內部使用節點選擇器就非常合適了。
HTML示例代碼:
下面的一些示例,我們還是使用這個HTML代碼進行節點選擇器的講解。
這里,我們先來教會大家如何獲取節點的名稱屬性以及內容,示例如下:
運行之後,效果如下:
一般來說一個節點的子節點有可能很多,通過上面的方式獲取,只能得到第一個。如果要獲取一個標簽的所有子節點,這里有2種方式。先來看代碼:
運行之後,效果如下:
如上面代碼所示,我們有2種方式獲取所有子節點,一種是通過contents屬性,一種是通過children屬性,2者遍歷的結果都是一樣的。
既然能獲取直接子節點,那麼獲取所有子孫節點也是肯定可以的。BeautifulSoup庫給我們提供了descendants屬性獲取子孫節點,示例如下:
運行之後,效果如下:
同樣的,在實際的爬蟲程序中,我們有時候也需要通過逆向查找父節點,或者查找兄弟節點。
BeautifulSoup庫,給我們提供了parent屬性獲取父節點,同時提供了next_sibling屬性獲取當前節點的下一個兄弟節點,previous_sibling屬性獲取上一個兄弟節點。
示例代碼如下:
運行之後,效果如下:
對於節點選擇器,博主已經介紹了相對於文本內容較少的完全可以這么做。但實際的爬蟲爬的網址都是大量的數據,開始使用節點選擇器就不合適了。所以,我們要考慮通過方法選擇器進行先一步的處理。
find_all()方法主要用於根據節點的名稱、屬性、文本內容等選擇所有符合要求的節點。其完整的定義如下所示:
【實戰】還是測試上面的HTML,我們獲取name=a,attr={"class":"aaa"},並且文本等於text="Python板塊"板塊的節點。
示例代碼如下所示:
運行之後,效果如下所示:
find()與find_all()僅差一個all,但結果卻有2點不同:
1.find()只查找符合條件的第一個節點,而find_all()是查找符合條件的所有節點2.find()方法返回的是bs4.element.Tag對象,而find_all()返回的是bs4.element.ResultSet對象
下面,我們來查找上面HTML中的a標簽,看看返回結果有何不同,示例如下:
運行之後,效果如下:
首先,我們來了解一下CSS選擇器的規則:
1..classname:選取樣式名為classname的節點,也就是class屬性值是classname的節點2.#idname:選取id屬性為idname的節點3.nodename:選取節點名為nodename的節點
一般來說,在BeautifulSoup庫中,我們使用函數select()進行CSS選擇器的操作。示例如下:
這里,我們選擇class等於li1的節點。運行之後,效果如下:
因為,我們需要實現嵌套CSS選擇器的用法,但上面的HTML不合適。這里,我們略作修改,僅僅更改
4. 如何使用Python和xml.etree.ElementTree解析xml文件獲取其節點
<?xmlversion="1.0"encoding="utf-8"?>
<root>
<bodyname="lyc">
<age>110</age>
</body>
<bodyname="l"age="10">
</body>
</root>
######################
#coding=UTF8
fromxml.etreeimportElementTree
#xmlText=open("xml.txt").read()
#root=ElementTree.fromstring(xmlText)
root=ElementTree.parse("xml.txt")
bodys=root.getiterator("body")
#getiterator方法獲取
print"getiterator"
printbodys
printdir(bodys[0])
print"attrib:",bodys[0].attrib
print"tag:",bodys[0].tag
print"text",bodys[0].text
#getchildren方法獲取
print"getchildren"
children=bodys[0].getchildren()
printchildren
print"attrib:",children[0].attrib
print"tag:",children[0].tag
print"text:",children[0].text
#find
print"find"
children=root.find("body")
printchildren
print"attrib:",children.attrib
print"tag:",children.tag
print"text:",children.text
#findall
print"findall"
children=root.findall("body")
printchildren
print"attrib:",children[0].attrib
print"tag:",children[0].tag
print"text:",children[0].text
5. Python3 解析 XML
4.獲取某節點的所有子節點
5.獲取某節點的值
6.修改完成後 將舊的根節點形成一個xml tree ,再將新的tree寫入文件
6. python爬蟲lxml基本用法
python3環境下安裝命令
用lxml解析html,利用etree.HTML解析字元串將字元串解析從html格式的文件, 經過處理後,部分缺失的節點可以自動修復,並且還自動添加了 body、html 節點
通過 / 或 // 即可查找元素的子節點或子孫節點。
選擇 li 節點的所有直接 a 子節點xpath為://li/a
標簽[@屬性=「」]
@text()
/@屬性
[contains(@屬性,"值")]
7. 怎麼用python獲取xml文件的所有節點。
假如我們有個xml文檔如下:example.xml
<?xml version="1.0" encoding="UTF-8"?>
<BIT>
<GeneralDescription>
<name>Matlab</name>
<DateTime>2008-09-10 23:16:48</DateTime>
</GeneralDescription>
<AMatrix>1,2,3;4,5,6;7,8,9</AMatrix>
</BIT>
首先,要解析xml文檔,需要導入一個模塊
>>> from xml.dom.minidom import parse
(1)然後載入一個xml文檔
>>> xmldoc = parse("J:/homeword/example.xml")
>>> print xmldoc.toxml()
<?xml version="1.0" ?>
<BIT>
<GeneralDescription>
<name>Matlab</name>
<DateTime>2008-09-10 23:16:48</DateTime>
</GeneralDescription>
<AMatrix>1,2,3;4,5,6;7,8,9</AMatrix>
</BIT>
>>>
上面是可以查看這個文檔的內容。
Toxml方法列印出了node風格的xml,如果節點是Document結果,則列印出整個xml文檔。否則只列印出本節點所屬內容。
(2)如何獲取子節點
>>> xmldoc.childNodes
[<DOM Element: BIT at 0x1223af8>]
>>>
每一個node都有一個childNodes的屬性,他是一個node對象的列表,注意的是,一個Document只有一個子節點,上例中就是BIT這個節點,它屬於Document節點。
因為是列表,所以也可以同用列表索引,xmldoc.childNodes[0]
>>> BIT_element = xmldoc.firstChild
>>> BIT_element
<DOM Element: BIT at 0x1223af8>
>>> print BIT_element.toxml()
<BIT>
<GeneralDescription>
<name>Matlab</name>
<DateTime>2008-09-10 23:16:48</DateTime>
</GeneralDescription>
<AMatrix>1,2,3;4,5,6;7,8,9</AMatrix>
</BIT>
>>>
(3)獲得某一個節點的文本
>>> BIT_element.childNodes
[<DOM Text node "
">, <DOM Element: GeneralDescription at 0x1223be8>, <DOM Text node "
">, <DOM Element: AMatrix at 0x1223e40>, <DOM Text node "
">]
>>>name = (BIT_element.childNodes[1]).childNodes[1]
>>> >>> name.childNodes[0].data
u'Matlab'
>>>
8. python 怎樣爬取div class=cont 裡面的p span
實現方法如下:
載入到XmlDocument,查找p子節點(XPath),如果要在子節點內繼續查找,用遞歸;
string patten_block="<div class=\"wm_sktq_l\">[\\s\\S]*</div>"
string patten_p="<p>[\\s\\S]*</p>" 用組獲取。
9. python elementtree 判斷節點是否有子節點
lxml takes all the pain out of XML.
Stephan Richter
lxml是Python語言里和XML以及HTML工作的功能最豐富和最容易使用的庫。lxml是為libxml2和libxslt庫的一個Python化的綁定。它與眾不同的地方是它兼顧了這些庫的速度和功能完整性,以及純Python API的簡潔性,大部分與熟知的ElementTree API兼容但比之更優越。
安裝lxml:
要求:需要Python2.3或更後的版本
使用easy_install工具,以超級用戶或管理員的角色run下面的命令:
easy_install lxml
在windows下,最好指定版本號:easy_install lxml==2.2.6
使用lxml進行開發
lxml.etree指南
通常使用lxml.etree的方式
>>> from lxml import etree
Element類,一個Element是ElementTree API的主要容器類,大部分的XML tree功能都是通過這個類來訪問的。Elements可以非常容易地通過Element工廠方法來創建。
>>> root = etree.Element("root")
元素的XML tag名字是通過tag屬性來訪問的
>>> print root.tag # root
Elements是在XML樹狀結構中組織的,為創建子元素並將它們加到父元素上,可以使用append()方法。
>>> root.append( etree.Element("child1") )
我們還有更高效的方法:SubElement工廠方法,它使用和Element工廠方法相同的參數,不過額外需要父節點作第一個參數:
>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")
可以使用tostring()方法來看得到的XML
>>> print etree.tostring(root, pretty_print=True)
<root>
<child1/>
<child2/>
<child3/>
</root>
元素是列表
>>> child = root[0]
>>> print child.tag
child1
>>> print len(root)
3
>>> root.index(root[1]) # lxml.etree only!
1
列印所有子節點:
>>> children = list(root)
>>> for child in root:
... print(child.tag)
child1
child2
child3
可以使用insert()方法插入新的子節點:
>>> root.insert(0, etree.Element("child0"))
刪除子節點:
>>> root[0] = root[-1] # this moves the element!
>>> for child in root:
... print(child.tag)
child3
child1
child2
如果想把一個元素拷貝到不同的地方,需要創建一個獨立的deep 。
>>> from import deep
>>> element = etree.Element("neu")
>>> element.append( deep(root[1]) )
>>> print(element[0].tag)
child1
>>> print([ c.tag for c in root ])
[』child3』, 』child1』, 』child2』]
getparent()返回父節點:
>>> root is root[0].getparent() # lxml.etree only!
True
元素的兄弟或鄰居節點是通過next和previous屬性來訪問的
The siblings (or neighbours) of an element are accessed as next and previous elements:
>>> root[0] is root[1].getprevious() # lxml.etree only!
True
>>> root[1] is root[0].getnext() # lxml.etree only!
True
帶屬性的元素
XML元素支持屬性,可以用Element工廠方法直接創建。
>>> root = etree.Element("root", interesting="totally")
>>> etree.tostring(root)
b』<root interesting="totally"/>』
可以使用set和get方法訪問這些屬性:
>>> print root.get("interesting")
totally
>>> root.set("interesting", "somewhat")
>>> print root.get("interesting")
somewhat
也可以使用attrib性質的字典介面
>>> attributes = root.attrib
>>> print(attributes["interesting"])
somewhat
>>> print(attributes.get("hello"))
None
>>> attributes["hello"] = "Guten Tag"
>>> print(attributes.get("hello"))
Guten Tag
>>> print(root.get("hello"))
Guten Tag
元素可以包含文字:
>>> root = etree.Element("root")
>>> root.text = "TEXT"
>>> print(root.text)
TEXT
>>> etree.tostring(root)
』<root>TEXT</root>』
如果XML用在(X)HTML中,文本也可以在不同的元素中顯示:
<html><body>Hello<br/>World</body></html>
元素有tail屬性,它包含XML 樹中元素直接跟的,直到下個元素的文本。
>>> html = etree.Element("html")
>>> body = etree.SubElement(html, "body")
>>> body.text = "TEXT"
>>> etree.tostring(html)
b』<html><body>TEXT</body></html>』
>>> br = etree.SubElement(body, "br")
>>> etree.tostring(html)
b』<html><body>TEXT<br/></body></html>』
>>> br.tail = "TAIL"
>>> etree.tostring(html)
b』<html><body>TEXT<br/>TAIL</body></html>』
10. Python怎麼把一個xml文件的部分節點拷貝到另一個xml文件的根節點或子節點去,求大神指教詳細代碼新手一個
用lxml庫把兩個xml都載入上來,用xpath方法可以優美的提取你想要的節點,再組合成新etree對象,最後保存file.思路就是這樣