Python程序员联盟程序员程序猿阵线联盟-汇总各类技术干货

Python爬虫:细说列表识别提取

2017-12-20  本文已影响440人  Tony带不带水
天冷要保暖

  上次文章后不少小伙伴私信我,对此感兴趣,希望我讲讲列表识别的细节问题。于是有了今天这篇文章。还是先再提一下本算法的核心思想。

1.可疑列表区域提取

  在进行可疑列表区域提取之前需要做一些预处理:因为selenium只能定位到页面上的可见元素,所以先用selenium的find_elements_by_xpath("//a")获取所有可见的<a>,并对定位到的元素创建新属性canSee并赋值yeap:self.__web_driver.execute_script("arguments[0].setAttribute('can-see','yeap');", link)(其实你想属性叫什么就叫什么),然后就清洗完毕了。
  接下来用lxml库的etree定位到dom树(这里将html直接说成dom树是为了后面提取最小父节点时候好理解)上所有canSee属性是True的<a>标签节点。将该节点假如列表A,以三个元素为单位扫描该列表,如下图。

可疑列表区域扫描过程示意图
Tips:

  在三大步骤中,只有这一步是在做加法,剩下的步骤基本是在过滤做减法了,所以尽可能的将可疑列表区域收入列表。

代码流程参考:
def tag_a_min_father_node(self):
    """
    计算提取可疑列表区域        
    :return: [xpath1,xpath2,xpath3,...]
    """
    links_Ele = []
    father_list = []
    # 预处理-将可见<a>设置属性can-see
    self.watch_links()

    root = etree.HTML(self.driver.page_source)
    Eleroot = etree.ElementTree(root)
    temp_total_path = []
    links =  Eleroot.findall('//a[@cansee]')
    self.LOG.info("all links after filter: {}".format(len(links)))
    # 识别时忽略JavaScript,因为后续步骤没有上下文环境
    links_Ele = [(x.xpath("string(.)")..strip(),\
                  Eleroot.getpath(x), \
                  x.attrib.get("href","")) \
                  for x in links \
                  if x.xpath("string(.)"). and len(x.xpath("string(.)").strip()) > 1 and \
                       self.anchor_black_regx.search(x.xpath("string(.)").strip()) is None\
                      and self.debar_extension_name_regex.search(x.attrib.get("href","")) is None \
                      and not x.attrib.get("href","").startswith("java")\
                      and not x.attrib.get("href","").startswith("#") # 不要锚链接
                     ]
    # 元素清洗
    # 相邻标签相同href,合并
    # 如果匹配到反向特征 legitimate = False
    legitimate, links_Ele = self.clean_links_Ele(links_Ele)

    if legitimate:
        # 扫描有效链接,提取最小父节点xpath
        for idx in xrange(len(links_Ele)-2):
            # 每次取三个元素
            now = links_Ele[idx: idx+3]
            is_list, father_xpath = self.get_list_father_xpath(now)
            if is_list:
                # 符合列表逻辑
                father_list.append(father_xpath)

    return list(set(father_list))

2.过滤不在主视图区域的可疑列表

代码流程参考:

def judge_list_xpath(self):
    """
    判断获取到的列表xpath是否在主视图区域
    :return:[xpath1,xpath2]
    """
    a_list= []
    list_xpath = []
    result = []
    # 获取可疑列表区域
    list_xpath = self.get_page_list()

    if list_xpath:
        for item in list_xpath:
            a_size_list = []
            try:
                a_list = self.driver.find_elements_by_xpath(item + '//a')
            except:
                self.LOG.error("{}:{}无法找到该xpath" .format(self.driver.current_url, item + '//a'))

            for element in a_list:
                a_size_list.append(element.size['width'])
            # 有的html可能不规范,会出现定位不到元素的情况
            max_a_size = max(a_size_list) if len(a_size_list) > 0 else 0
            if max_a_size == 0: continue
            # 判断size最大的a标签的位置
            content = self.driver.find_element_by_xpath(item)
            # 超过3000认为异常情况
            if content.size['width'] > 3000:
                continue
            # 这句无所谓,原来想用来过滤导航栏之类的,现在后续有更好解决方案
            if (content.size['height']) < 70 and content.size['height'] != 0:
                continue
            # 判断x轴中位线
            if self.check_x(content):
                    result.append(item)
    self.LOG.info("list after view filter: {}".format(result))
    return result

3.可扩展规则簇

  以上步骤基本可以保证你获得一个穿过了x中位线的列表区域,但极有可能混进去一些奇奇怪怪的东西,或者漏了一些重要的东西。这时候就需要你的这些规则了,比如:

至此列表区域识别已经完成,输出值为列表区域的xpath。
有问题的话私聊我吧,没问题的话点赞吧~

上一篇 下一篇

猜你喜欢

热点阅读