簡體   English   中英

如何將輸出轉換為列表來計算它的數量?

[英]How to convert output to list to count it amount?

我編寫了一個腳本來解析網頁並獲取鏈接數量('a'標簽):

import urllib
import lxml.html
connection = urllib.urlopen('http://test.com')
dom =  lxml.html.fromstring(connection.read())
for link in dom.xpath('//a/@href'):
    print link

腳本的輸出:

./01.html
./52.html
./801.html
http://www.blablabla.com/1.html
#top

如何將其轉換為列表來計算鏈接數量? 我使用link.split()但它得到了我:

['./01.html']
['./52.html']
['./801.html']
['http://www.blablabla.com/1.html']
['#top']

但我想得到:

[./01.html, ./52.html, ./801.html, http://www.blablabla.com/1.html, #top]

謝謝!

link.split()嘗試拆分鏈接本身。 但您必須使用代表所有鏈接的實體。 在你的情況下: dom.xpath('//a/@href')

所以這必須幫助你:

links = list(dom.xpath('//a/@href'))

並通過內置的len函數獲取長度:

print len(links)
list(dom.xpath('//a/@href'))

這將采用dom.xpath返回的迭代器並將每個項放入列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM