2016-12-03 78 views
0

我是新來的網絡刮和python一般,但我有點卡住如何糾正我的功能。我的任務是從一個特定的字母開始刮掉單詞的網站,並返回匹配的單詞列表,最好使用正則表達式。感謝您的時間,下面是我的代碼。Webscrape沒有美麗的湯

import urllib 
import re 

def webscraping(website): 
    fhand = urllib.urlopen(website).read() 
    for line in fhand: 
     line = fhand.strip() 
     if line.startswith('h'): 
      print line 
webscraping("https://en.wikipedia.org/wiki/Web_scraping") 
+2

爲什麼你不想用美麗的湯? –

+0

我們還沒有學會如何在我的編程課程中使用美麗的湯,我試過的所有資源都使用它 – Mayhem

+1

不要嘗試它並重新發明輪子。 Web刮板將使您的生活比嘗試使用正則表達式來刮擦更容易。如果頁面發生變化,那麼所有的正則表達式將不再提取所需的數據,具體取決於頁面被修改的方式以及您的正則表達式不再提取您需要的值。 – serk

回答

1

要繼續前進,並說這個:

and return a list of the ones that match, preferably using regex. 

號您 絕對不應該使用正則表達式來解析HTML。這就是爲什麼我們擁有HTML分析器的原因。

使用BeautifulSoup,它的一切內置的,它是比較容易做這樣的事情:(未測試)

def webscraping(website): 

    fhand = urllib.urlopen(website).read() 
    soup = BeautifulSoup(fhand, "html.parser") 
    soup.find_all(text=lambda x: x.startswith('h')) 
0

從來沒有使用正則表達式來解析HTML,您可以用美麗的湯 這裏是一個示例

import urllib 
from BeautifulSoup import * 

todo = list() 
visited = list() 
url = raw_input('Enter - ') 
todo.append(url) 

while len(todo) > 0 : 
    print "====== Todo list count is ",len(todo) 
    url = todo.pop() 

    if (not url.startswith('http')) : 
     print "Skipping", url 
     continue 

    if (url.find('facebook') > 0) : 
     continue 

    if (url in visited) : 
     print "Visited", url 
     continue 

    print "===== Retrieving ", url 

    html = urllib.urlopen(url).read() 
    soup = BeautifulSoup(html) 
    visited.append(url) 

    # Retrieve all of the anchor tags 
    tags = soup('a') 
    for tag in tags: 
     newurl = tag.get('href', None) 
     if (newurl != None) : 
      todo.append(newurl)