如何解决在模态框架Selenium Python中单击“阅读更多”按钮不止一次
我想获得所有客人的评论。但是有些评论的文字很长,可用来单击“阅读更多”按钮以查看所有文字。问题是按钮的数量取决于评论。我可以加载并获得所有评论,但一切正常,但我不知道“了解更多”按钮。如何点击模式中的所有“阅读更多”按钮
链接URL:https://th.airbnb.com/rooms/27194960/reviews?source_impression_id=p3_1600195106_a%2FYGw9bddHf%2BMfUE
下面的代码是从URL获取HTML文本的功能。有2个条件,我们将重点关注条件2,该条件会获得您可以在if-else条件下看到的评论--- if review:。
def get_pageswithSelenium(roomid,review,page_send):
#session = requests.Session()
#ua = UserAgent()
#headers = {'User-Agent':ua.random}
if not(review):
url = "https://th.airbnb.com/rooms/{}?source_impression_id=p3_1600195106_a%2FYGw9bddHf%2BMfUE".format(roomid)
else:
url = "https://th.airbnb.com/rooms/{}/reviews?source_impression_id=p3_1600195106_a%2FYGw9bddHf%2BMfUE".format(roomid)
print("selenium url: "+url)
browser = webdriver.Chrome(executable_path=r"C:\chromedriver_win32\chromedriver.exe")
browser.get(url)
if review:
browser.implicitly_wait(20)
element_inside_popup = browser.find_element_by_xpath('//div[@class="_yzu7qn"]//a')
for j in range(page_send):
element_inside_popup.send_keys(Keys.END)
time.sleep(5)
print(str(j))
#find all 'read more' button and click (code here)
else:
browser.implicitly_wait(12)
html = browser.page_source
bsObj_bd = BeautifulSoup(html,'html')
return bsObj_bd
我将Selenium与Chrome驱动程序配合使用。谢谢大家的光临,提前帮助。
解决方法
使用wait
和try-except
检查“更多”按钮是否存在。
有关wait
的更多信息,请参见this link。
#find all 'read more' button and click (code here)
from selenium.webdriver.support import expected_conditions as EC
try:
buttons = WebDriverWait(driver,10).until(
EC.visibility_of_all_elements_located((By.XPATH,"//div[@class='_yzu7qn']//button[@class='_ejra3kg']")))
except TimeoutException:
print("no read more")
else:
for button in buttons:
button.click()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。