【问题标题】:Python Webscraping Selenium and BeautifulSoup (Modal window content)Python Webscraping Selenium 和 BeautifulSoup(模态窗口内容)
【发布时间】:2017-05-24 01:27:12
【问题描述】:

我正在尝试学习网页抓取(我是个新手)。我注意到在某些网站上(例如 Quora),当我单击一个按钮时,屏幕上会出现一个新元素。我似乎无法获得新元素的页面来源。我希望能够获取新弹出窗口的页面源并获取所有元素。请注意,您需要有一个 Quora 帐户才能了解我的问题。

我有一段代码,你可以使用 beautifulsoup、selenium 和 chromedriver:

from selenium import webdriver
from bs4 import BeautifulSoup
from unidecode import unidecode 
import time

sleep = 10
USER_NAME = 'Insert Account name' #Insert Account name here
PASS_WORD = 'Insert Account Password' #Insert Account Password here
url = 'Insert url' 
url2 = ['insert url']
#Logging in to your account
driver = webdriver.Chrome('INSERT PATH TO CHROME DRIVER')
driver.get(url)
page_source=driver.page_source
if 'Continue With Email' in page_source:
    try:
        username = driver.find_element(By.XPATH, '//input[@placeholder="Email"]')
        password = driver.find_element(By.XPATH, '//input[@placeholder="Password"]')
        login= driver.find_element(By.XPATH, '//input[@value="Login"]')
        username.send_keys(USER_NAME)
        password.send_keys(PASS_WORD)
        time.sleep(sleep)
        login.click()
        time.sleep(sleep)
    except:
        print ('Did not work :( .. Try again')
else:
    print ('Did not work :( .. Try different page')


下一部分将转到相关网页并(“尝试”)收集有关特定问题的关注者的信息。

for url1 in url2:        
    driver.get(url1)
    source = driver.page_source
    soup1 = BeautifulSoup(source,"lxml")  
    Follower_button = soup1.find('a',{'class':'FollowerListModalLink QuestionFollowerListModalLink'})
    Follower_button2 = unidecode(Follower_button.text)
    driver.find_element_by_link_text(Follower_button2).click()

####Does not gives me correct page source in the next line####
    source2=driver.page_source
    soup2=BeautifulSoup(source2,"lxml")

    follower_list = soup2.findAll('div',{'class':'FollowerListModal QuestionFollowerListModal Modal'})
    if len(follower_list)>0:
        print 'It worked :)'
    else:
        print 'Did not work :('

但是,当我尝试获取关注者元素的页面源时,我最终得到的是主页的页面源,而不是关注者元素。谁能帮我获取弹出的follower元素的页面源??我在这里没有得到什么。

注意: 重新创建或查看我的问题的另一种方法是登录到您的 Quora 帐户(如果有的话),然后与关注者一起解决任何问题。如果您单击屏幕右下方的关注者按钮,则会弹出一个窗口。我的问题本质上是获取此弹出窗口的元素。


更新 - 好的,所以我一直在阅读,似乎该窗口是一个模态窗口。有人帮我获取模式窗口的内容吗?

【问题讨论】:

  • 尝试切换到窗口句柄。可能是?实际上,这是不可能的,因为源已经在那里,只是元素不可见。
  • 我已经试过了。似乎只有一个把手。所以无法切换。 :(

标签: python selenium beautifulsoup modal-dialog selenium-chromedriver


【解决方案1】:

问题已解决。我所要做的就是添加一行:

time.sleep(sleep_time)

在产生点击之后。问题是因为最初没有等待时间,页面源没有得到更新。然而,随着 time.sleep 足够长(可能因网站而异),页面源终于得到更新,我能够获得所需的元素。 :) 学习到教训了。耐心是网络抓取的关键。花了一整天的时间试图弄清楚这一点。

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 2021-01-11
    • 2021-11-01
    • 2023-03-05
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多