2017-10-12 188 views
2

我是從techcrunch.com的本地存檔中抓取的網頁。我使用正則表達式來排序併爲每篇文章抓取每個標題,但是我的輸出仍然保持最後一次出現。Python-正則表達式輸出最後一次出現[HTML Scraping]

def extractNews(): 
selection = listbox.curselection() 

if selection == (0,): 
    # Read the webpage: 
    response = urlopen("file:///E:/University/IFB104/InternetArchive/Archives/Sun,%20October%201st,%202017.html") 
    html = response.read() 

    match = findall((r'<h2 class="post-title"><a href="(.*?)".*>(.*)</a></h2>'), str(html)) # use [-2] for position after) 


    if match: 
     for link, title in match: 
      variable = "%s" % (title) 


    print(variable) 

和電流輸出

Heetch提高$ 12百萬重啓其共乘服務

這是整個網頁的最後一個標題,如下圖所示(最後一次出現)

網站/圖像看起來像 this並且每個文章塊組成爲標題相同的代碼S:

<h2 class="post-title"><a href="https://web.archive.org/web/20171001000310/https://techcrunch.com/2017/09/29/heetch-raises-12-million-to-reboot-its-ride-sharing-service/" data-omni-sm="gbl_river_headline,20">Heetch raises $12 million to reboot its ridesharing service</a></h2>

我不明白爲什麼它不斷造成這一最後一場比賽。我已經通過如https://regex101.com/這樣的網站跑過它,它告訴我,我只有一個匹配,而不是在我的程序中輸出的匹配。任何幫助將不勝感激。

編輯:如果有人知道的方式寫入到一個.html文件時不同<h1></h1>標籤之間單獨顯示每個匹配的結果,這將意味着很多:)我不知道這是否是正確的,但我想你使用[ - #]作爲引用的位置/比賽嗎?

回答

0

正則表達式很好,但你的問題是在這裏的循環。

if match: 
for link, title in match: 
    variable = "%s" % (title) 

您的變量在每次迭代中被覆蓋。這就是爲什麼你只能看到它最後一次迭代循環的價值。

你可以做一些沿着這些路線:

if match: 
variableList = [] 
for link, title in match: 
    variable = "%s" % (title) 
    variableList.append(variable) 

print variableList 

另外,一般來說,我會建議不要使用正則表達式來解析HTML(按照famous answer)。

如果你還沒有熟悉BeautifulSoup,你應該。這是一個非正則表達式解決方案,使用BeautifulSoup從你的html頁面挖掘出所有的h2後期標題。

from bs4 import BeautifulSoup 
soup = BeautifulSoup(html, "html.parser") 
soup.findAll('h2', {'class':'post-title'}) 
+0

非常感謝你:)這個答案很完美!沒想到要做個清單。儘管我限制使用任何外部庫,但我會用美麗的湯。 – mattappdev

相關問題