嵌套的隐藏标签在python中进行抓取

问题描述 投票:0回答:1

首先,首先是python和web抓取的新手。

我有一个需要抓取的页面。我正在寻找很多来源,并且无法弄清楚嵌套隐藏标签的刮擦。该页面需要登录并能够获取我的代码成功执行的可见数据。但是,当涉及在div标记内废弃嵌套元素时,它找不到任何东西。

HTML(在onClick()事件之前)

<div id="topMenu" style="width: 1920px; position: relative; top: 46px;" onclick="menu(event);" oncontextmenu="javascript:if(!event.ctrlKey){return RightClickPopUp(event);}">
   <span id="3" class="cSub" lcid="63" lccl="Item" style="visibility: hidden; display: none; top: 20px;"> 
        <span id="1" menuname="Cancel" parentid="63" class="Menu01" showmenu="010">Cancel</span>
   </span>

   <span id="3" class="cSub" lcid="63" lccl="Item" style="visibility: hidden; display: none; top: 20px;"> 
        <span id="1" menuname="Cancel" parentid="63" class="Menu01" showmenu="010">Cancel</span>
   </span>
</div>

点击div(由多个按钮组成)后,第一个span标签变为可见,然后跳转到其适当的嵌套span标签。我的问题是访问最里面的span中的文本。

HTML(onClick()事件之后)

<div id="topMenu" style="width: 1920px; position: relative; top: 46px;" onclick="menu(event);" oncontextmenu="javascript:if(!event.ctrlKey){return RightClickPopUp(event);}">
     <span id="3" class="cSub" lcid="63" lccl="Item" style="visibility: visible; display: inline; top: 20px;"> 
          <span id="1" menuname="Cancel" parentid="63" class="Menu01" showmenu="010">Cancel</span>
     </span>

      <span id="3" class="cSub" lcid="63" lccl="Item" style="visibility: visible; display: inline; top: 20px;"> 
          <span id="1" menuname="Cancel" parentid="63" class="Menu01" showmenu="010">Cancel</span>
      </span>
</div>

Python代码

import mechanize 
from bs4 import BeautifulSoup
import urllib
import http.cookiejar as cookielib
from bs4 import BeautifulSoup as soup


cj = cookielib.CookieJar()
br = mechanize.Browser()

br.set_cookiejar(cj)
br.open("LOGIN_URL")

br.select_form(nr=0)
br.form['USER'] = 'un'
br.form['PASSWORD'] = 'pwd'
br.submit()

check = br.response().read()
print(check) //login success 

my_url = br.open("URL_I_NEED_TO_SCRAPE").read()
page_soup = soup(my_url, "html.parser")
containers = page_soup.find("div",{"id":"topMenu"})

这段代码可以帮助我获得div,但内部没有任何内容。有没有办法得到目前隐藏在这个spans内的div

python web-scraping beautifulsoup mechanize
1个回答
0
投票

有很多方法可以提取内部隐藏元素,如span,src和alt标记。

containers = page_soup.find("div",{"id":"topMenu"})
top_span=containers.find_all('span',class_='cSub')
print(len(top_span)
#len of spans is two
inner_span=top_span[0].find('span')
inner_span_text=inner_span.text
class_inside_inner_span=inner_span['class']

有关网页抓取的更多详情,请关注我的帖子:“https://github.com/rajat4665/web-scraping-with-python

© www.soinside.com 2019 - 2024. All rights reserved.