2016-12-03 76 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)