samedi 23 septembre 2017

If statement search for string returns false but printed output displays string

I'm using this function to search a site to see if a particular item i'm interested in s on sale. It first grabs the html from the page, then searches for an item i'm interested. When it finds the item it adds a number of the following lines (dictated by the rangenumber) to the variable 'endresult'. It then searches for the keyword ("sale") in endresult, at which point I'd like it to notify me if the keyword is present or not.
When I print endresult the output contains the keyword, but the if statement at the very end of the function always returns "keyword is missing" despite this and I can't work out why.

def bargainscraper(self, website, item, keyword,rangenum):
                request = urllib.request.Request(website)
                response = urllib.request.urlopen(request)
                data = response.read()
                html = str(data)
                data1 = html2text.html2text(html)
                fw = open('result1.txt', 'w')
                fw.write(str(data1))
                fw.close()
                with open('result1.txt', 'r') as f:
                        for line in f:
                                if item in line:
                                        for x in range(rangenum):
                                                endresult = str(f.readline())
                                                print (endresult)
                if keyword in endresult:
                        print ("keyword is present")
                else:
                        print ("keyword is missing")

Aucun commentaire:

Enregistrer un commentaire