Home > Blockchain >  Python and bs4 trying to make an if statement based on results
Python and bs4 trying to make an if statement based on results

Time:12-17

What I am trying to do is use Beautifulsoup to scrap a specific website and if it sees the "add to cart" button it notifies me that its there and if it doesn't it'll loop. Im kind of stuck at the beginning of this trying to get it to work. Below is from when I inspect the website as well as the script I was working on. Any assistance would be gratefully appreciated

    <div >
  <button type="button"  data-id="45399" data-cart-qty="0" data-title="Walking Dead       Compendium TP Vol 03">
     <im g src="/images/cart.png" alt="Add to Cart">
      " Add to Cart"
    </button>
  <button type="button"  data-id="45399" data-code="AUG150497D" data-title="random title ">…</button>
from bs4 import BeautifulSoup
import requests

def main():
    requests.get("https://www.websiteurl.com")
    doc = BeautifulSoup(result, "html.parser")
    if doc.find_all(class_='btn addtocart', text=" Add to Cart "):
        print("Stuff")

CodePudding user response:

Wrap the code in a loop, and break out when you find what you want.

from bs4 import BeautifulSoup
import requests, time

def main():
    while True:
        requests.get("https://www.websiteurl.com")
        doc = BeautifulSoup(result, "html.parser")
        if doc.find(class_='btn addtocart', text=" Add to Cart "):
            print("Stuff")
            break

        time.sleep(1)

CodePudding user response:

Instead of using an if statement, wrap the doc.find_all call into a for loop:

for result in doc.find_all(class_='btn addtocart', text=" Add to Cart "):
    print("stuff")

With this, you also have the resulting line in a variable that can be used to pull out specific data if desired.

  • Related