我想學習webscraping(我是一個總新手)。我注意到在某些網站上(例如。Quora),當我點擊一個按鈕並在屏幕上出現一個新元素時。我似乎無法獲得新元素的頁面源代碼。我希望能夠獲得新彈出窗口的頁面源並獲取所有元素。請注意,您需要有一個Quora帳戶才能瞭解我的問題。
我的,你可以使用使用beautifulsoup,硒和chromedriver守則的一部分:Python網頁抓取Selenium和BeautifulSoup(Modal窗口內容)
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 :('
然而,當我試圖讓追隨者元素的網頁源代碼,我最終得到了主網頁,而不是跟隨元素的網頁源代碼。任何人都可以幫助我獲得彈出的追隨者元素的頁面源?我不在這裏。
注: 重建或在看我的問題的另一種方法是登錄到您的Quora帳戶(如果有的話),然後去與追隨者的任何問題。如果您點擊屏幕右下角的追隨者按鈕,則會彈出一個窗口。我的問題基本上是要獲得這個彈出窗口的元素。
更新 - 好了,所以我一直在閱讀了一下,好像窗口是模態窗口。有人幫我獲取模態窗口的內容嗎?
嘗試切換到窗口句柄。也許?實際上,這是不可能的,因爲源已經存在,只有元素不可見。 – ProFan
我已經試過了。似乎只有一個句柄。所以沒有可能的切換。 :( – Prometheus