2014-06-23 88 views
1

因此可以說我有以下基本網址http://example.com/Stuff/preview/v/{id}/fl/1/t/。網頁上有許多不同的{id}在被解析。我想在HTML頁面中找到與此模板匹配的所有鏈接。查找與HTML頁面中特定網址模板匹配的所有鏈接

我可以使用xpath來匹配模板的一部分//a[contains(@href,preview/v]或者只是使用正則表達式,但我想知道是否有人知道使用xpath和正則表達式匹配整個模板的更優雅的方式,所以它的快速和匹配絕對正確。

謝謝。

編輯。我在示例頁面上對它進行了計時。通過我的互聯網連接和100次試驗,迭代平均需要0.467秒,BeautifulSoup需要0.669秒。

另外,如果你有Scrapy,它可以使用Selectors

data=get(url).text 
    sel = Selector(text=data, type="html") 
    a=sel.xpath('//a[re:test(@href,"/Stuff/preview/v/\d+/fl/1/t/")]//@href').extract() 

平均時間上,這也是0.467

回答

3

使用lxml,因爲lxml supports xpath 1.0xpath 1.0doesn't support regular expression search不能使用在xpath表達式正則表達式。

相反,你可以找到使用iterlinks()一個網頁上的所有環節,在它們之間迭代並檢查href屬性值:

import re 
import lxml.html 

tree = lxml.html.fromstring(data) 

pattern = re.compile("http://example.com/Stuff/preview/v/\d+/fl/1/t/") 
for element, attribute, link, pos in tree.iterlinks(): 
    if not pattern.match(link): 
     continue 
    print link 

另一種選擇是使用BeautifulSoup HTML解析器:

import re 
from bs4 import BeautifulSoup 

data = "your html" 
soup = BeautifulSoup(data) 

pattern = re.compile("http://example.com/Stuff/preview/v/\d+/fl/1/t/") 
print soup.find_all('a', {'href': pattern}) 

要使BeautifulSoup解析速度更快,您可以let it use lxml

soup = BeautifulSoup(data, "lxml") 

此外,您還可以使用一個SoupStrainer類,可以讓你分析,而不是整個頁面只有特定的網頁部分。

希望有所幫助。

+0

這有效,但我更傾向於使用xpath,因爲BeautifulSoup速度相當慢,而且我正在做這個匹配很多次。迭代可能會更快,但還沒有測試過。 – Artii

+0

@Artii請參閱更新。儘管如此,我仍然在研究答案。 – alecxe

+0

@Artii完成編輯,看看你還有什麼問題。謝謝。 – alecxe

相關問題