Python / Selenium组合多个列表并通过可见文本显示

时间:2018-05-18 19:25:30

标签: python list selenium selenium-webdriver web-scraping

我目前正在教自己如何使用Python / Selenium。

我有一段代码,列出了网页上所有可用的衬衫,然后列出了所有可用的颜色,但我希望衬衫/颜色一起显示,而不是两个单独的列表。

这是我到目前为止所得到的:

shirts = driver.find_elements_by_xpath("""//*[@id="container"]/article/div/h1/a""")
for shirt in shirts:
    text = shirt.text
    print text
colors = driver.find_elements_by_xpath("""//*[@id="container"]/article/div/p/a""")
for color in colors:
    text = color.text
    print text

以下是上述代码的结果:

Contrast Zip Up Hooded Sweatshirt
Contrast Zip Up Hooded Sweatshirt
Contrast Zip Up Hooded Sweatshirt
Contrast Zip Up Hooded Sweatshirt
Contrast Zip Up Hooded Sweatshirt
Contrast Zip Up Hooded Sweatshirt
Contrast Crewneck
Contrast Crewneck
Contrast Crewneck
Contrast Crewneck
Contrast Crewneck
Contrast Crewneck
Jet Sleeve Zip Up Hooded Sweatshirt
Jet Sleeve Zip Up Hooded Sweatshirt
Jet Sleeve Zip Up Hooded Sweatshirt
Jet Sleeve Zip Up Hooded Sweatshirt
Jet Sleeve Zip Up Hooded Sweatshirt
Navy
Red
Heather Grey
Dark Green
Light Brown
Black
Heather Grey
Light Brown
Black
Dark Green
Red
Navy
Violet
Light Pine
Black
White
Navy

1 个答案:

答案 0 :(得分:1)

使用zip方法:

shirts = driver.find_elements_by_xpath("//*[@id='container']/article/div/h1/a")
colors = driver.find_elements_by_xpath("//*[@id='container']/article/div/p/a")
for shirt, color in zip(shirts, colors):
    shirt_text = shirt.text
    color_text = color.text
    print shirt_text, color_text