【问题标题】:Webscrape w/o beautiful soup没有漂亮汤的网页剪贴画
【发布时间】:2017-04-18 01:08:52
【问题描述】:

一般来说,我是网络抓取和 python 的新手,但我对如何更正我的函数有点卡住了。我的任务是抓取以特定字母开头的单词站点并返回匹配的单词列表,最好使用正则表达式。感谢您抽出宝贵时间,下面是我的代码。

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")

【问题讨论】:

  • 为什么不想用美汤呢?
  • 在我的编程课上我们还没有学会如何使用漂亮的汤,我尝试的所有资源都在使用它
  • 不要尝试重新发明轮子。网络爬虫将使您的生活比尝试使用正则表达式进行爬取更容易。如果页面发生更改,那么您的所有正则表达式将不再提取您需要的数据,具体取决于页面的修改方式以及您的正则表达式是否不再获取您需要/想要的值。

标签: python regex python-2.7 function web-scraping


【解决方案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'))

【讨论】:

    【解决方案2】:

    永远不要使用正则表达式来解析 HTML,你可以使用 Beautiful Soup 这是一个例子

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2021-11-12
      • 2017-08-15
      • 2022-01-20
      • 1970-01-01
      相关资源
      最近更新 更多