首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >漂亮的Soup get_all()迭代在N个结果之后停止

漂亮的Soup get_all()迭代在N个结果之后停止
EN

Stack Overflow用户
提问于 2017-11-09 00:51:44
回答 1查看 224关注 0票数 0

下面的Python脚本运行时没有出现错误,但只返回前6个购物中心的结果。

代码语言:javascript
复制
from bs4 import BeautifulSoup
from selenium import webdriver

stores_link = "http://www.ardenfair.com/Directory"

stores_driver = webdriver.Firefox()
stores_driver.get(stores_link)

stores_html = stores_driver.page_source
stores_soup = BeautifulSoup(stores_html, "html5lib")

for outer_stores_html in stores_soup.find_all(class_="result-item uk-scrollspy-init-inview uk-scrollspy-inview uk-animation-fade"):
    try:
        store_name = outer_stores_html.find_all(class_="result-description font-style-4")[0].text
        store_level_phone = outer_stores_html.find_all(class_="search-result-details font-style-1")[0].text

        print("-->" + store_name, store_level_phone)
    except IndexError:
        continue

stores_driver.close()

我正在查看HTML,我在find_all()方法中搜索的div对于每个商店来说都是相同的,页面上有超过6个。为什么我只找到前六名?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-09 01:05:32

这是因为对于fading in and out的动画来说,classes元素的css classes是动态变化的。您应该只使用那些不改变的类。我快速查看了它,我认为您应该使用下面的for循环:

代码语言:javascript
复制
for outer_stores_html in stores_soup.find_all(class_="result-item"):
    try:
        store_name = outer_stores_html.find_all(class_="result-description")[0].text
        store_level_phone = outer_stores_html.find_all(class_="search-result-details")[0].text

        print("-->" + store_name, store_level_phone)
    except IndexError:
        continue

注意我为元素使用的类名。我只对每个find_all()函数使用了一个。

结果:我得到了许多结果(我认为184个结果)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47192182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档