如何使用硒和美丽汤在 div 中抓取 div 和 iframe 的内容



我目前正在抓取格式化的页面:

<div id="container>
   <script>Script that cause iframe contents to load correctly</script>
   <iframe>Contents of iFrame</iframe>
   <script>More scripts</script>
</div>

我可以轻松抓取页面,但这不会抓取 iframe 内容,因此我用以下方式切换了框架:

driver.switch_to.frame(iframeElement)

这允许我获取 iframe 内容。这让我现在想到了一个问题,即如何获取容器div,并将抓取的 iframe 的内容插入抓取的div 中。页面的设置方式,在 iframe 之前有动态脚本,允许 iframe 的内容工作,这就是为什么我需要将 iframe 内容嵌入到抓取的div 中。

相关蟒蛇如下:

driver.get(url)
iframeElement = driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(iframeElement)
time.sleep(3) #Wait for the contents to generate
# driver.switch_to_default_content() #Commented out, but I know to use this to exit out of the iframe
html = driver.page_source
soup=BeautifulSoup(html, features="lxml")
print(soup)
print(soup.find("div", {"id": "Container"})) #Let's see the HTML of the container
soupStr=str(soup)
Con = str(soup.find("div", {"id": "Container"})) #Create a variable with JUST the container HTML
with open('iframeWithinDiv.html', 'w', encoding='utf-8') as f_out: #Save the file
    f_out.write(soupStr)```

你可以通过使用execute_script和一点jquery(你可以使用纯JS(将其附加到以下div:)

html = driver.page_source
soup=BeautifulSoup(html, features="lxml")
print(soup)
print(soup.find("div", {"id": "Container"})) #Let's see the HTML of the container
soupStr=str(soup)
Con = str(soup.find("div", {"id": "Container"}))1
#### Append your variable to the given string within wrap ###
driver.execute_script("$('#container').val('newhtmlcontent')")

最新更新