0 python selenium web-scraping
我是一个硒菜鸟,一直在努力用 python 完成工作。我试图从这个页面迭代所有用户评论(“partial_entry”类)https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe")
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or560-TAP-Portugal#REVIEWS"
driver.get(url)
for i in driver.find_elements_by_xpath("//div[@class='wrap']"):
print i.find_element(By.XPATH, '//p[@class="partial_entry"]')
print i.text
print "=============================================="
# THIS IF BLOCK IS NECESSARY, I CANT DO AWAY WITH THIS ONE
if i.find_elements(By.CSS_SELECTOR,"#REVIEWS .googleTranslation>.link"):
print "======YES TRANSLATION AVAILABLE========"
Run Code Online (Sandbox Code Playgroud)
即使我每次在 for 循环中选择一个不同的元素,但它一遍又一遍地打印相同的元素。(我必须保留最后一个 if 块并且不能取消它,所以无论解决方案是什么,它也必须包含 if 块)
======编辑==================
即使这也不起作用(根据http://selenium-python.readthedocs.io/locating-elements.html,这实际上应该起作用)。我不知道硒是怎么回事!!!!!
print i.find_element(By.CSS_SELECTOR, 'p.partial_entry')
Run Code Online (Sandbox Code Playgroud)
输出:
NoSuchElementException:
Run Code Online (Sandbox Code Playgroud)
1.i.find_element(By.XPATH, '//p[@class="partial_entry"]')在第二个循环中迭代时不断重复获取第一个元素的原因是开始//尝试从根/顶级定位元素,而不是作为 的后代元素i。因此,p.partial_entry对于外循环的每次迭代,它只会不断返回第一个元素。
要搜索i匹配的后代元素p[@class="partial_entry"],xpath 应该以.//. 这就是点的作用。
2.对于行print i.find_element(By.CSS_SELECTOR, 'p.partial_entry'):
singlefind_element要么返回第一个找到的元素,要么在没有找到时抛出错误。有一些 'div.wrap's 没有那个后代元素,所以你会得到NoSuchElementException.
该find_elements(注意“S”)方法返回元素的列表或一个空列表,如果没有找到,而不是一个错误。
所以把所有这些放在一起:
>>> for i in driver.find_elements_by_xpath("//div[@class='wrap']"):
... for ent in i.find_elements_by_xpath('.//p[@class="partial_entry"]'):
... print ent.text
... if i.find_elements_by_css_selector('#REVIEWS .googleTranslation>.link'):
... print 'translation available'
... print # output clarity
...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你为什么要混合像find_elements_by_xpath('...')with 之类的东西find_element(By.XPATH, '...')?坚持一种模式。