Hello everyone. This is Nakagawa. This is the first post in a long time. I usually make business web applications using Java at my company, but in general life I often scrape with Python. Especially, I am addicted to automatic blog updates and automatic follow-ups such as sns. So this time, I tried a simple blog update using Python and selenium.
qiita.py
from selenium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
class LivedoorAuto:
def __init__(self):
options = webdriver.ChromeOptions()
#chrome://version See profile path
options.add_argument("")
#executable_In path, enter the path of chromedriver
self.bot = webdriver.Chrome(executable_path="", chrome_options=options)
def livedoor(self):
bot = self.bot
#Blog post page url
bot.get("")
wait = WebDriverWait(bot,60)
entry_title = wait.until(expected_conditions.visibility_of_element_located((By.ID,"entry_title")))
entry_title.send_keys("Hello")
while True:
try:
entry_body = wait.until(expected_conditions.visibility_of_element_located((By.ID,"editor_1_f")))
entry_body.send_keys("Hello Everyone")
break
except TimeoutException:
print("timeout")
continue
sleep(2)
bot.find_element_by_class_name("quickSocialMessage").send_keys("Hello")
ed = LivedoorAuto()
ed.livedoor()
It is a code that writes the title hello and the words Hello Everyone in the article content.
When you first access the url, you will be taken to the login page, but if you log in many times, it may be treated as spam, so we try to keep the login information in the session from the beginning. How to keep your login information in selenium is explained in detail on the following page. If you want to keep your site logged in the next time you run Selenium
It's not too difficult, but I didn't have much information like this on the internet, so I wrote it. I hope it will be helpful for you.
Recommended Posts