代码之家  ›  专栏  ›  技术社区  ›  Tag

检查Python是否已写入目标文本

  •  -4
  • Tag  · 技术社区  · 10 年前

    我正在编写一个代码,从大量网页上删除可见文本的选定部分。以下是其中的一部分:

                    divTag = soup.find_all("div", {'id':'articleBody'})
                    for tag in divTag:
                        pTags = tag.find_all("p") 
                        for tag in pTags:
                            print >>f, tag.text
    

    如何检查Python是否找到并编写了目标文本 ,如果刮取不成功,将链接放在一边(列表)?

    我在这里没有找到答案,我也不知道在哪里可以查看文档。

    1 回复  |  直到 10 年前
        1
  •  0
  •   estebanpdl    10 年前

    这是了解python是否找到您要查找的文本的另一种方法:

    import requests
    from bs4 import BeautifulSoup
    
    urls = ['https://www.google.com']
    for i in range(len(urls)):
        r = requests.get(urls[i])
        soup = BeautifulSoup(r.content, 'lxml')
        items = soup.find_all('p')
        for item in items:
            if "2016 - Privacidad - Condiciones" in item.text:
                print "Python has found the targeted text"
    

    如果python没有找到 text ,您需要使用 remove() 方法