0

I want to add if statement there:

if website_link and phone is not found than write N,N

This Script is typing if website link is not found it type N and if phone is not found it type N

I Want Also Add This:

If Website And Phone is not found Type N,N

Here is my Code:

from selenium import webdriver 
import csv
import pandas
import itertools

with open("sans.csv",'r') as s:
    s.read()

driver = webdriver.Firefox()

url = 'https://www.yelp.com/biz/konomama-san-francisco?osq=Restaurants'

driver.get(url)
website_link = driver.find_elements_by_css_selector('.text--offscreen__373c0__1SeFX+ .link-size--default__373c0__1skgq')

phone = driver.find_elements_by_css_selector('.text--offscreen__373c0__1SeFX+ .text-align--left__373c0__2pnx_')

items = len(website_link)
with open("sans.csv", 'a',encoding="utf-8") as s:
    for combination in itertools.zip_longest(website_link, phone):
         s.write(f'{combination[0].text if combination[0] else "N"}, {combination[1].text if combination[1] else "N"}\n')

driver.close()

print("Done")

Thanks!

Hamza Lachi
  • 1,046
  • 7
  • 25

2 Answers2

2

You can add else to the for loop. It will run in case the loop doesn't when website_link and phone are empty

with open("sans.csv", 'a', encoding="utf-8") as s:
    for combination in itertools.zip_longest(website_link, phone):
        s.write(f'{combination[0].text if combination[0] else "N"}, {combination[1].text if combination[1] else "N"}\n')
    else:
        s.write('N, N')

For more info about for - else structure see this answer.

Guy
  • 46,488
  • 10
  • 44
  • 88
  • Exactly the way I would have used. Could you add a brief explanation of how `for ... else ...` clause works in python as the asker seems to be starting with Python? – Adirio Nov 11 '19 at 13:43
  • @Adirio This is a good [explanation](https://stackoverflow.com/a/9980160/5168011) – Guy Nov 11 '19 at 13:49
  • 2
    I do know what `for ... else ...` clause does, I was suggesting to add that info into the answer. The link is actually quite nice, I would include it in your answer. – Adirio Nov 11 '19 at 14:14
  • @guy This is typing n in next line if something found – Hamza Lachi Nov 13 '19 at 05:06
  • @HamzaLachi just add new line character `s.write('N, N\n')` – Guy Nov 13 '19 at 05:18
  • @Guy I Add This My Question Is for example if website and phone found it will write website and phone Error when it type phone and website it will insert new line and add N,N if website and phone Found – Hamza Lachi Nov 13 '19 at 05:34
0

may be he wants the iterator to iterate and check for None in website_link and phone

with open("sans.csv", 'a',encoding="utf-8") as s:
    for combination in itertools.zip_longest(website_link, phone):
         s.write(f'{combination[0].text if combination[0] else "N"}, {combination[1].text if combination[1] else "N"}\n')
         if(website_link == None) and (Phone == None):
               s.write('N,N')