使用Python Selenium

时间:2017-02-05 13:26:45

标签: python selenium automated-tests

我有这个页面:

Tripadvisor

对于每个发布的评论,title属性中都有相应的日期,

检查一下:

<span class="ratingDate relativeDate" title="4 February 2017">Reviewed yesterday </span>

因此,对于每个发布的评论,title属性中都有一个日期,我的问题是我无法从评论中获取所有日期。

我尝试使用此代码:

def Dates():
datediv = driver.find_elements_by_css_selector('div > div.col2of2 > div > div.wrap > div.rating.reviewItemInline > span.ratingDate.relativeDate')
dateatt = datediv.get_Attribute("title")
for date in dateatt:
    print(date.text)

但它仍然不起作用,我得到

的错误
AttributeError: 'list' object has no attribute 'get_Attribute'

我哪里错了?

修改 好的,现在我已经从每个页面中删除了用户名,日期,标题和整个评论,但仅限于IDLE。我想把每页的抓取数据放到一个字典中,然后将它导出到json中,或者直接把它放到excel表中。

使用字典的方法非常混乱,因为我实际上不明白如何使用值独立更新不同的键。

content = {}

def mainfunction():
#Hotel Name
hname = driver.find_element_by_id('HEADING').text


#User Names
usernames = driver.find_elements_by_class_name('scrname')
for 

#Dates
datediv = driver.find_elements_by_css_selector('div > div.col2of2 > div > div.wrap > div.rating.reviewItemInline > span.ratingDate.relativeDate')


#Review Title
titlesdiv = driver.find_elements_by_class_name('isNew')
#for titles in titlesdiv:
#print(titles.find_element_by_class_name('noQuotes').text)


#Reviews 
linkdiv = driver.find_element_by_class_name('expandLink')
linkspan = linkdiv.find_element_by_class_name('ulBlueLinks')
linkspan.click()

try:
    WebDriverWait(driver,10).until(ec.presence_of_element_located((By.CLASS_NAME,"no_padding")))
    close1 = driver.find_element_by_css_selector('body > div> span > div.ui_close_x')
    close1.click()

except TimeoutException:
    print ("Loading took too much time!")


reviews = driver.find_elements_by_css_selector(' div > div.col2of2 > div > div.wrap > div > div > p')
for review in reviews:
    print(review.text)


#push the contents to the dictionary



#Move to next page
nextpage()


#To follow successive pages and scrape the content
def nextpage():
    nextpage = driver.find_element_by_css_selector('#REVIEWS >   div.deckTools.btm.test > div >   a.nav.next.rndBtn.ui_button.primary.taLnk').click()
    try:
        WebDriverWait(driver,10).until(ec.presence_of_element_located((By.CLASS_NAME,"pcb")))
        close2 = driver.find_element_by_class_name('ui_close_x')
    close2.click()
    except TimeoutException:
        print ("Loading took too much time!")

    mainfunction()

1 个答案:

答案 0 :(得分:2)

datediv是列表。你需要迭代它

datediv = driver.find_elements_by_css_selector('div > div.col2of2 > div > div.wrap > div.rating.reviewItemInline > span.ratingDate.relativeDate')
for dateatt in datediv:
    print(dateatt.get_attribute("title"))