V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
saximi
V2EX  ›  Python

请教 BeautifulSoup 语法的问题

  •  
  •   saximi · 2017-09-04 19:42:25 +08:00 · 1601 次点击
    这是一个创建于 2424 天前的主题,其中的信息可能已经有所发展或是发生改变。

    以下代码用于从 http://buy.ccb.com/ 网站爬取手机栏目的地址,在 while 模块中逐个提取链接并判断该链接的说明文字是否为“手机”,是的话就返回该链接,否则继续提取其余链接, 如果链接都遍历完毕还没找到,则在 try 模块中捕捉该异常并返回 None。

    from urllib.request import urlopen   
    from bs4 import BeautifulSoup    
    import re   
        
    baseUrl="http://buy.ccb.com/" 
    def getMobileLinks(articleUrl):   
        html = urlopen(baseUrl+articleUrl)   
        bsObj = BeautifulSoup(html,'lxml')   
        isFound = 0 
        url = bsObj.find("div", {"class":"lists"}).find("a", href=True)  
        while isFound == 0 : 
            print("a=",url)  
            h=re.search(r'手机', ''.join(url)) 
            if h != None : 
                isFound = 1  
                return url.attr("href") 
            else: 
                try: 
                    url = bsObj.find("div", {"class":"lists"}).find_next("a", href=True)   #语句 1 
                except Exception as e:      #语句 2 
                    print("Not Found!",e) 
                    return None 
             
    links = getMobileLinks("")   
    print('links=',links)  
    
    上面代码反复输出如下一行内容: 
    a= http://buy.ccb.com/searchproducts/pv_0_0_0_0.jhtml?hotKeySize=6&hotMerchantList=%24hotMerchantList.size%28%29&catId=&selectCatId=&qa=&query=APPLE " style="margin: 0px 3px 0px 0px;" target="_blank">苹果 
    
    
    我的问题如下: 
    1、语句 1 用于获取 BeautifulSoup 找到的下一个"a"标签对象,虽然执行没有报错但是出现了死循环,看来是 find_next 找下一个"a"标签对象的语法不对,请问正确的语法应该如何写呢? 
    
    2、语句 2 的本意是在 BeautifulSoup 返回的"a"标签对象都遍历完毕时报错,但是不知道没有"a"标签对象可找时会抛出什么异常? 
    恳请大家指点,感谢! 
    
    
    3 条回复    2017-09-05 22:49:17 +08:00
    Trim21
        1
    Trim21  
       2017-09-05 08:35:22 +08:00 via iPad
    用 Soup.find_all()找到所有的 a 标签,然后针对所有的标签遍历。
    saximi
        3
    saximi  
    OP
       2017-09-05 22:49:17 +08:00
    @quinoa42 看了这个材料,但是好像没有提到 find_next 如果没有结果可找时会返回什么错误呢?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2730 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 15:51 · PVG 23:51 · LAX 08:51 · JFK 11:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.