Python 抓取网页、最大化收集信息的策略

Python 抓取网页、最大化收集信息的策略,python,web-scraping,beautifulsoup,classification,Python,Web Scraping,Beautifulsoup,Classification,问题是: 用户注册一个站点,可以从8个工作类别中选择一个,也可以选择跳过此步骤。我想根据电子邮件地址中的域名,将跳过该步骤的用户分类为工作类别 当前设置: 使用BeautifulSoup和nltk的组合,我浏览了一下主页,并查找到网站上包含“about”一词的页面链接。我也刮了那一页。我已经复制了这篇文章末尾的代码片段 问题是: 我没有得到足够的数据来制定一个好的学习计划。我想知道我的抓取算法是否是为了成功而设置的——换句话说,我的逻辑中是否存在漏洞,或者是否有更好的方法来确保我有一个好的文本块

问题是:

用户注册一个站点,可以从8个工作类别中选择一个,也可以选择跳过此步骤。我想根据电子邮件地址中的域名,将跳过该步骤的用户分类为工作类别

当前设置:

使用BeautifulSoup和nltk的组合,我浏览了一下主页,并查找到网站上包含“about”一词的页面链接。我也刮了那一页。我已经复制了这篇文章末尾的代码片段

问题是:

我没有得到足够的数据来制定一个好的学习计划。我想知道我的抓取算法是否是为了成功而设置的——换句话说,我的逻辑中是否存在漏洞,或者是否有更好的方法来确保我有一个好的文本块来描述一家公司所做的工作

(有关)守则:

将bs4作为bs导入
将httplib2作为http导入
导入nltk
#url中只有这些字符有效
允许的字符=“abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvxyzo123456789-。~:/?#[]@!$&'()*+,;=”
类网页(对象):
定义初始化(自,域):
"""
建造师
:param domain:要查看的URL
:类型域:str
"""
self.urlhttp://www.“+域
尝试:
self.\u获取\u主页()
除了:#这里有具体的捕获吗?
self.homepage=无
尝试:
self.\u了解我们()
除:
self.about_us=无
def_获取_主页(自我):
"""
打开主页,查找重定向
"""
进口稀土
web=http.http()
响应,pg=web.request(self.url)
#检查重定向:
如果int(response.get('content-length',251))<250:
new_url=re.findall(r'(https?:/\S+),pg)[0]
如果len(新url):#否则我无能为力。。。
self.url=''.join(如果x在允许的字符中,则x代表新的\u url中的x)
响应,pg=web.request(self.url)
self.homepage=self.\u parse\u html(nltk.clean\u html(pg))
self.\u raw\u homepage=pg
了解我们(自我):
"""
打开主页,找到“关于我们”页面,并将其内容存储在
一串
"""
汤=bs.BeautifulSoup(自选生的主页)
links=[x代表soup.findAll('a'),如果x.get('href',None)不是None]
如果x.get('href','')中的'about',则链接中的x的about=[x.get('href')。lower()]
#需要找到关于我们的信息吗
关于我们页面=无
在大约:
位=a.strip(“/”).split(“/”)
如果len(位)==1:
关于我们页面=位[0]
elif“about”以位[-1]为单位。下限()
关于我们页面=位[-1]
#否则,假设最短字符串是关于pg的顶级字符串。
如果“关于我们”页面为“无”和“关于”:
关于我们页面=min(关于,键=len)
self.about_us=无
如果“关于我们”页面不是“无”:
self.about_us_url=self.url+'/'+关于_us_页面
web=http.http()
响应,pg=web.request(self.about\u-us\u-url)
如果int(response.get('content-length',251))>250:
self.about_us=self._parse_html(nltk.clean_html(pg))
定义解析html(自身、原始文本):
"""
清除网页中的html。清除
-所有'\n'和'\r'字符
-所有零长度字
-非ascii的所有unicode字符(即,&…)
"""
lines=[x.strip()表示原始文本中的x.splitlines()]
all_text=''.join([x代表x,如果len(x)])#长度为零的字符串
返回[x代表所有文本中的x。如果len(x)和x[0]!='&',则拆分(“”)

这超出了您的要求,但我会考虑调用已收集此信息的外部数据源。例如,在网上可以找到这样的服务。并非所有可编程Web上的数据都是最新的,但似乎有很多API提供程序都在那里。

既然您已对此进行了标记,那么如果您提及url或提供要解析的网页片段,这将非常有用。从您提供的代码(用于连接网页)很难理解确切的问题。我这里有一个大约6000个URL的字符串,所以我不确定列表是否能提供信息。我想知道是否有办法改进上面的抓取/解析算法,使其尽可能以最通用的方式工作。当然,任何一般性的提示都将不胜感激。添加一个示例足以提供一些上下文。1 >>> 0@AaronD重点是,对于给定的任何域,我都希望这样做。如果我举一个我正在尝试刮取的域的例子,我会得到十几个答案,告诉我如何刮取该域。但这还不够好,因为我必须为我得到的每个新域更改算法。这有意义吗?换句话说,我不知道谁将注册我的网站,所以我必须假设完全的通用性。顺便说一句,我将把抓取和处理分为两个步骤。首先,下载信息并将原始结果存储在文件或数据库中。然后你可以多次重新分析你的结果,直到你得到一个好的结果,而不必重击你正在查看的公司的网站。非常好。我以前没听说过可编程网络。
import bs4 as bs
import httplib2 as http
import nltk


# Only these characters are valid in a url
ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;="


class WebPage(object):
    def __init__(self, domain):
        """
            Constructor

            :param domain: URL to look at
            :type domain: str
        """
        self.url = 'http://www.' + domain

        try:
            self._get_homepage()
        except: # Catch specific here?
            self.homepage = None

        try:
            self._get_about_us()
        except:
            self.about_us = None

    def _get_homepage(self):
        """
            Open the home page, looking for redirects
        """
        import re

        web = http.Http()
        response, pg = web.request(self.url)

        # Check for redirects:
        if int(response.get('content-length',251)) < 250:
            new_url = re.findall(r'(https?://\S+)', pg)[0]
            if len(new_url): # otherwise there's not much I can do...
                self.url = ''.join(x for x in new_url if x in ALLOWED_CHARS)
                response, pg = web.request(self.url)

        self.homepage = self._parse_html(nltk.clean_html(pg))
        self._raw_homepage = pg

    def _get_about_us(self):
        """
            Soup-ify the home page, find the "About us" page, and store its contents in a
            string
        """
        soup = bs.BeautifulSoup(self._raw_homepage)
        links = [x for x in soup.findAll('a') if x.get('href', None) is not None]
        about = [x.get('href') for x in links if 'about' in x.get('href', '').lower()]

        # need to find about or about-us
        about_us_page = None
        for a in about:
            bits = a.strip('/').split('/')
            if len(bits) == 1:
                about_us_page = bits[0]
            elif 'about' in bits[-1].lower():
                about_us_page = bits[-1]

        # otherwise assume shortest string is top-level about pg.
        if about_us_page is None and len(about):
            about_us_page = min(about, key=len)

        self.about_us = None
        if about_us_page is not None:
            self.about_us_url = self.url + '/' + about_us_page
            web = http.Http()
            response, pg = web.request(self.about_us_url)
            if int(response.get('content-length', 251)) > 250:
                self.about_us = self._parse_html(nltk.clean_html(pg))

    def _parse_html(self, raw_text):
        """
            Clean html coming from a web page. Gets rid of
                - all '\n' and '\r' characters
                - all zero length words
                - all unicode characters that aren't ascii (i.e., &...)
        """
        lines = [x.strip() for x in raw_text.splitlines()]
        all_text = ' '.join([x for x in lines if len(x)]) # zero length strings
        return [x for x in all_text.split(' ') if len(x) and x[0] != '&']