Issue
I'm having trouble saving my output to a file. I'm using the following script (note this is an Australian website):
from selenium import webdriver
import time
chrome_path =r"C:\Users\Tom\Desktop\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://pointsbet.com.au/basketball/NBA")
time.sleep(2)
driver.find_element_by_xpath("""/html/body/div[1]/div[2]/sport-competition-component/div[1]/div[2]/div[1]/div/event-list/div[1]/event/div/header/div[1]/h2/a""").click()
time.sleep(2)
posts = driver.find_elements_by_class_name("market")
for post in posts:
print(post.text)
with open('output12.txt',mode ='w') as f:
f.write(str(post))
the output in the txt file come out as:
<selenium.webdriver.remote.webelement.WebElement (session="af079b982b14f33d736b6745ad6e9648", element="0.8397874328987758-6")>
it should come out as something like this (depending on the websites data at that point in time):
HEAD TO HEAD Memphis Grizzlies 1.55 Miami Heat 2.53 LINE Memphis Grizzlies -4.0 1.92 Miami Heat +4.0 1.92 TOTAL POINTS Over 195.5 1.87 Under 195.5 1.96 NAME A BET FEATURE Mike Conley and Marc Gasol To Combine For 41+ Points 2.50
The above is how the text prints when the script is run.
ANy help would be great
thanks- new to stack overflow- this is fantastic
Solution
Correct your for
loop as follows and tell if it works for you : note that the with open(...) ...
must be inside the for
loop, not outside ! You also need to open the file in append
mode.
for post in posts:
print(post.text)
with open('output12.txt',mode ='a') as f:
f.write(post.text)
The other solution, more efficient one, as pointed out by @Tommy could be:
with open('output12.txt',mode ='w') as f:
for post in posts:
print(post.text)
f.write(post.text)
Answered By - Neroksi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.