如何在Python中使用Selenium为亚马逊搜索页面找到正确的“布局”?

问题描述 投票:0回答:1

我正在使用Python 3.5从amazon.com上删除一些产品信息。在自动执行“search-grabinfo”过程的过程中,我发现当页面布局发生变化时会中断。目前我知道2种不同的布局,我希望有一个if形式的条件:

if layout = DefaultLayout:
    #do something...
elif layout = ListLayout:
    #do something differently...
else:
    pass 

我能够找到这个布局选项的<div class>标签,但是我无法使用selenium来获取它在我的if条件下使用

对于默认布局:<div id="searchTemplate" class="searchTemplate defaultLayout so_us_en" >...</div> 对于列表布局:<div id="searchTemplate" class="searchTemplate listLayout so_us_en" >...</div>

使用XPath似乎不是一个选项,因为它的形式为"/html/body/table/tbody/tr[1350]/td[2]/span/span[4]"with tr [i]不是常数

python python-3.x selenium web-scraping selenium-chromedriver
1个回答
1
投票

如果我理解了问题,您可以使用此模板:

# check if defaultLayout is on the page
defaultLayout = driver.find_elements_by_xpath("//div[@id = 'searchTemplate' and @class = 'searchTemplate defaultLayout so_us_en']")

# check if listLayout is on the page
listLayout = driver.find_elements_by_xpath("//div[@id = 'searchTemplate' and @class = 'searchTemplate listLayout so_us_en']")

if not defaultLayout:
    #do something...
elif not listLayout:
    #do something differently...
else:
    pass 

这个模板的想法是获取元素列表并检查列表是否为空。

注意:我使用过find_elements,因为它返回找到的元素列表,如果没有找到元素,它不会抛出任何异常,只返回一个空列表。

© www.soinside.com 2019 - 2024. All rights reserved.