代码之家  ›  专栏  ›  技术社区  ›  timurichk

网站对分析器隐藏页脚

  •  0
  • timurichk  · 技术社区  · 8 年前

    我想在网站上找到捐款按钮 The University of British Columbia .

    捐款按钮位于页脚,在分类为“span7”的div中

    然而,当被刮擦时,html将div与没有任何内容的div合并。

    我的程序以direct div作为源运行得很好:

    from bs4 import BeautifulSoup as bs
    import re
    
    site = '''<div class="span7" id="ubc7-footer-menu"><div class="row-fluid"><div class="span6"><h3>About UBC</h3><div><a href="https://cdn.ubc.ca/clf/ref/contact">Contact UBC</a></div><div><a href="https://cdn.ubc.ca/clf/ref/about">About the University</a></div><div><a href="https://cdn.ubc.ca/clf/ref/news">News</a></div><div><a href="https://cdn.ubc.ca/clf/ref/events">Events</a></div><div><a href="https://cdn.ubc.ca/clf/ref/careers">Careers</a></div><div><a href="https://cdn.ubc.ca/clf/ref/gift">Make a Gift</a></div><div><a href="https://cdn.ubc.ca/clf/ref/search">Search UBC.ca</a></div></div><div class="span6"><h3>UBC Campuses</h3><div><a href="https://cdn.ubc.ca/clf/ref/vancouver">Vancouver Campus</a></div><div><a href="https://cdn.ubc.ca/clf/ref/okanagan">Okanagan Campus</a></div><h4>UBC Sites</h4><div><a href="https://cdn.ubc.ca/clf/ref/robson">Robson Square</a></div><div><a href="https://cdn.ubc.ca/clf/ref/centre-for-digital-media">Centre for Digital Media</a></div><div><a href="https://cdn.ubc.ca/clf/ref/medicine">Faculty of Medicine Across BC</a></div><div><a href="https://cdn.ubc.ca/clf/ref/asia">Asia Pacific Regional Office</a></div></div></div></'''
    
    html = bs(site, 'html.parser')
    link = html.find('a', string=re.compile('(?)(donate|donation|gift)')) 
    
    #returns proper donation URL
    

    但是,使用站点不起作用

    from bs4 import BeautifulSoup as bs
    import requests
    import re
    
    site = requests.get('https://www.ubc.ca/')
    
    html = bs(site.content, 'html.parser')
    link = html.find('a', string=re.compile('(?i)(donate|donation|gift)')) 
    
    #returns none
    

    我的解析器有问题吗?这是某种反刮策略吗?我注定了吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   nmog    8 年前

    我似乎找不到您提供的url上的“捐赠”按钮,但解析器本身并没有什么问题,只是您发送的get请求只给您最初从响应返回的html,而不是等待页面完全呈现。

    页面的某些部分似乎是由javascript填充的。你可以用 Splash ,用于呈现基于javascript的页面。你可以冲进去 Docker 很容易,只需向splash容器发出http请求,该容器将返回看起来与web浏览器中呈现的网页一样的html。

    虽然这听起来过于复杂,但实际上设置起来相当简单,因为您根本不需要修改docker映像,也不需要事先了解docker就可以让它工作。启动本地启动服务器只需要命令行中的一行:
    docker run -p 8050:8050 -p 5023:5023 scrapinghub/splash

    然后,只需修改python代码中的任何现有请求即可路由到splash:

    http://example.com/ 变成
    http://localhost:8050/render.html?url=http://example.com/