เบื้องต้นติดปัญหาในเรื่องของการวนลูป ตอนใช้ selenium ทำ automate test
โค้ดในส่วนของการวนลูปแล้วเมื่อ loop รอบแรกแล้วมันไม่ทำงานต่อ loop รอบที่ 2
โค้ด: เลือกทั้งหมด
continue_link = driver.find_element_by_tag_name('a')
title_list = driver.find_elements_by_xpath(
"//div[@class='category-list']//table[@class='category table table-striped table-bordered table-hover']/tbody/tr//a[@href]")
for web_link in title_list:
link = web_link.get_attribute("href")
driver.get(link)
driver.find_element_by_xpath("//input[@value='เรต']").click()
time.sleep(1)
อธิบายโค้ดแต่ละส่วน
1. โค้ดส่วนนี้ใช้ในการหา Tag 'a'
โค้ด: เลือกทั้งหมด
continue_link = driver.find_element_by_tag_name('a')
2. โค้ดส่วนนี้ทำการหา Session และ Element เพื่อนำมาแปลงเป็นลิ้งค์
โค้ด: เลือกทั้งหมด
title_list = driver.find_elements_by_xpath(
"//div[@class='category-list']//table[@class='category table table-striped table-bordered table-hover']/tbody/tr//a[@href]")
3. นำ Session และ Element มาแปลงเป็นลิ้งค์โดยการวนลูป
โค้ด: เลือกทั้งหมด
for web_link in title_list:
link = web_link.get_attribute("href")
ขั้นตอนต่อภายใน loop เมื่อแปลงลิ้งค์เสร็จแล้วทำการเปิดลิ้งค์ แรกภายใน loop
ต่อมาเมื่อเข้ามาใน Link ให้ทำการ กดปุ่มที่ชื่อว่า 'เรต' เพื่อทำการโหวตให้คะแนน
โค้ด: เลือกทั้งหมด
driver.find_element_by_xpath("//input[@value='เรต']").click()
และเมื่อคลิกเสร็จให้มีเวลาโหลดหน้าเว็บ 1 วิ
แต่เมื่อจบ loop แรกแล้วระบบ ไม่วนไปลูปที่ 2 โดยมีผล Error ดังนี้
โค้ด: เลือกทั้งหมด
Traceback (most recent call last):
File "/home/com003/PycharmProjects/m058/selenium_autorat.py", line 25, in <module>
link = web_link.get_attribute("href")
File "/home/com003/PycharmProjects/m058/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webelement.py", line 141, in get_attribute
self, name)
File "/home/com003/PycharmProjects/m058/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 627, in execute_script
'args': converted_args})['value']
File "/home/com003/PycharmProjects/m058/venv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
self.error_handler.check_response(response)
File "/home/com003/PycharmProjects/m058/venv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <a href="/บทความ/31-ความรู้ทั่วไป/5454-high-dynamic-range.html"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
ผลบนเว็บ
1. เมื่อเข้ามาหน้าเว็บ
https://www.mindphp.com และเข้า บทความ >> หมวความรู้ทั่วไป
2. จะเข้ามาในหน้าความรู้ทั่วไป และ ต้องการให้กดบทความแต่ละบทความ
3. เข้าบทความแรกแล้วกด ปุ่ม 'เรต' เมื่อกด เสร็จแล้วต้องการให้กลับไปที่ หน้าความรู้ทั่วไป แต่ระบบ ไม่กลับครับ
อยากรู้ว่าต้องทำยังไงครับ