Element是什么
回歸正題,大家暈頭轉腦的看完繁雜的語法之后,已經迫不及待寫點什么東西了,然后部分同學可能遇到了這個
<Element a at 0x39a9a80>
或者類似 Element a at 0x???????,這樣的一個值,某種意義上來說,當你打印變量的時候得到的這個值,其實它是一個列表,然后列表中的每一個值都是一個字典
from bs4 import BeautifulSoup from lxml import etree import requests gjc='SHKD-700' html = "http://www.btanv.com/search/"+gjc+"-hot-desc-1"#定義URL html = requests.get(html).content.decode('utf-8')#解碼URL dom_tree = etree.HTML(html)#解析成xml links = dom_tree.xpath("//a[@class='download']")#在xml中定位節點,返回的是一個列表 for index in range(len(links)): # links[index]返回的是一個字典 if (index % 2) == 0: print(links[index].tag) print(links[index].attrib) print(links[index].text)
實例解析
下面重點看看這個代碼,
print(links[index])
print(type(links[index]))
print(links[index].tag)#獲取<a>標簽名a
print(links[index].attrib)#獲取<a>標簽的屬性href和class
print(links[index].text)#獲取<a>標簽的文字部分
打印出來的是
<Element a at 0x3866a58>
<class 'lxml.etree._Element'>
a
{'href': 'magnet:?xt=urn:btih:7502edea0dfe9c2774f95118db3208a108fe10ca', 'class': 'download'}
磁力鏈接
該節點的html代碼為
<a href="magnet:xt=urn:btih:7502edea0dfe9c2774f95118db3208a108fe10ca" class="download">磁力鏈接</a>
總結
- Element類型是'lxml.etree._Element',某種意義來說同時是一個列表
- 列表的需要使用tag\attrib\text三個不同的屬性來獲取我們需要的東西
- 變量.tag獲取到的是標簽名是---字符串
- 變量.attrib獲取到的是節點標簽a的屬性---字典
- 變量.text獲取到的是標簽文本--字符串
from bs4 import BeautifulSoup
from lxml import etree
import requests
gjc='SHKD-700'
#定義URL
html = "http://www.btanv.com/search/"+gjc+"-hot-desc-1"
#解碼URL
html = requests.get(html).content.decode('utf-8')
#解析成xml
dom_tree = etree.HTML(html)
#在xml中定位節點,返回的是一個列表
links = dom_tree.xpath("//a[@class='download']")
for index in range(len(links)):
# links[index]返回的是一個字典
if (index % 2) == 0:
print(links[index].tag)
print(links[index].attrib)
print(links[index].text)
