The annual Tanabata is here again, the circle of friends is the rhythm of the screen. But it’s always someone else’s party. It’s like we only have dog food. Time flies and a lot of things have changed, but it seems like the only thing that never changes is your single status.



Single for a long time, we seem to feel that a person has nothing. But even if you’re enjoying your single life, you should stay in a “hookup” standby mode because boosting your hormones is good for your health.



In this everyone is in show of time, as a programmer we also want to operate! Send out your hormones! Today we are dedicated on Tanabata the strongest confession procedures! This program combined with data capture + wechat automatic message + timing task, to achieve a daily automatic timing to send your beloved TA: you meet and love days + love words + I love you picture. The details are as follows.





The message format is as follows:



    message = """Dear {}: Good morning, today is the first {} day you and NGU have been together ~ today he wants to say to you: {} last and most important! """.format("Your friend's name", str(inLoveDays), love_word)

Copy the code




The first field to fill in here is the title of the person, “inLoveDays” refers to the number of days you have met and been in love.



Love_word is every day for the ta carefully prepared love words content, of course, if you are good at writing can also write their own.









And last but not least! Different “I love you” pictures every day!









Program way of thinking



This program is run in windows10 + Python 3.6, the main library used in selenium, itchat, request. The program is mainly divided into two parts of the first data capture, some love words information and picture information. Another is using ItChat to automatically send messages to your friends.



Line information



If you are confident in your writing style, you can write your own love words. Of course, most people’s writing style is relatively poor like me, so at this time we can use the resources on the Internet, such as the following love words website.



Romantic love words _ classic sayings

www.binzz.com





When crawling this site, if you use the usual crawling method, namely using the request for the request, you will find that the data obtained by the page is garbled and incomplete. So for ease of use here, I used Selenium’s PhantomJS headless browser to get information about the site.



Through Selenium + xpath, we can easily obtain the love words on the web, and finally save the obtained data to the current directory “love_word.txt” for easy reading later.



Resources of Confession Pictures



In order to cooperate with the Tanabata confession procedures, I specifically went to find some pictures with “I love you” resources. Through the following post bar posts, we can obtain a large number of such resources.



http://tieba.baidu.com/p/3108805355









This post doesn’t have a strong anti-crawl, so I simply use request + re to get the image and save it to the “img” file in the current directory.



Before saving the image resource, I first check if there is an ‘IMG’ folder in the current directory, if not, it will be created automatically.



Vindicate program source code



The program mainly has 5 functions





crawl_Love_words()



This function uses Selenium + xpath to grab the lovetalk site’s resources and store them in the “love_word.txt” file in the current directory.



def crawl_Love_words():
    print("Grabbing love words...")
    browser = webdriver.PhantomJS()
    url = "http://www.binzz.com/yulu2/3588.html"
    browser.get(url)
    html = browser.page_source
    Selector = etree.HTML(html)
    love_words_xpath_str = "//div[@id='content']/p/text()"
    love_words = Selector.xpath(love_words_xpath_str)
    for i in love_words:
        word = i.strip("\n\t\u3000\u3000").strip()
        with open(love_word_path, "a") as file:
            file.write(word + "\n")
    print("Love words grab complete")

Copy the code


crawl_love_image()



This function is used to crawl posts with “I love you” images via request + re. The code is not complicated, and a simple one is written in the regular expression to match all the current image resources.



def crawl_love_image():
    print("Grabbing I love you picture...")
    for i in range(1, 22):
        url = "http://tieba.baidu.com/p/3108805355?pn={}".format(i)
        response = requests.get(url)
        html = response.text
        pattern = re.compile(r'
      
       . *? 
       . *? '
      *?>, re.S)
        image_url = re.findall(pattern, html)
        for j, data in enumerate(image_url):
            pics = requests.get(data)
            mkdir(pic_path)
            fq = open(pic_path + '\ \' + str(i) + "_" + str(j) + '.jpg'.'wb')  Download the image, save it and name it
            fq.write(pics.content)
            fq.close()
    print("Image capture completed")

Copy the code


mkdir(path)

This function is used to create a new folder in the current directory to store the corresponding data.

def mkdir(path):
    folder = os.path.exists(path)

    if not folder:  If no folder exists, create a folder
        os.makedirs(path)  # makedirs creates a file path if it does not exist
        print("--- new folder... -")
        print("--- OK ---")
    else:
        print("Saving picture...")

Copy the code


send_new()

This function uses itChat library to automatically send messages to your wechat friends. In this function I use datetime to calculate how long you met and fell in love with each other. And added a “hotReload=True” to login so you don’t have to log in every time you run the program. For more information about itChat, you can find it online.

def send_news():

    # Count the number of days
    inLoveDate = datetime.datetime(2018, 8, 15) # Time in love
    todayDate = datetime.datetime.today()
    inLoveDays = (todayDate - inLoveDate).days

    # Get sweet nothings
    file_path = os.getcwd() + '\ \' + love_word_path
    with open(file_path) as file:
        love_word = file.readlines()[inLoveDays].split(':')[1]

    itchat.auto_login(hotReload=True) # Hot start, no need to scan code multiple login
    my_friend = itchat.search_friends(name=u'Your friend name')
    girlfriend = my_friend[0]["UserName"]
    print(girlfriend)
    message = """Dear {}: Good morning, today is the first {} day you and NGU have been together ~ today he wants to say to you: {} last and most important! """.format("NGU", str(inLoveDays), love_word)
    itchat.send(message, toUserName=girlfriend)

    files = os.listdir(pic_path)
    file = files[inLoveDays]
    love_image_file = "D:\\img\\" + file
    try:
        itchat.send_image(love_image_file, toUserName=girlfriend)
    except Exception as e:
        print(e)

Copy the code


main()

The main() function is our main logic function, and the logical order of the program is specified in this function. In main(), I first judge whether there is a “love_word.txt” file under the current path, if there is a prompt corresponding information, if not, just go to crawl_Love_words() function, to grab some love words data online.

Secondly, we will judge whether there is an “IMG” folder under the current directory to determine whether we have picture resources. If not, we will execute crawl_love_image() to grab picture resources on the post bar.

Finally, when we have all the data we need, call send_news() to sort out the format of the data to send, and then automatically send a message to your TA.

Timing task

I mainly use while True simple implementation, by judging whether the current time is the time you need to send, to achieve the daily time.

if __name__ == '__main__':
    while True:
        curr_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        love_time = curr_time.split("") [1]if love_time == "13:14:00":
            main()
            time.sleep(60)
        else:
            print("Loving you every day is so wonderful, now time:" + love_time)

Copy the code


Vindicate program use tutorial

First of all, you download the corresponding source code, and the background reply “vindicate” can be obtained. Secondly, install the corresponding library in advance, and then run the program will display a Two-Dimensional code of wechat web login, scanning login can be.



Xiaobian added “hotReload=True” at login, so the program does not need to log in again the next time it runs.



conclusion

There is still a lot to add to this program. For example, for the sent message field, we can also continue to add weather information, constellation information, entertainment news, recent interesting, recent movies, and so on. You can add anything you can think of.

These information can be obtained on the Internet, as long as we through the same idea, first grab to the local, and then read. Of course, if you think the local storage will be deleted risk, then you can also save to the cloud, on the cloud storage.



For those who are interested in crawlers, data analysis and algorithms, please add the wechat official account TWcoding and let’s play Python together.



If it works for you.Please,star.



God helps those who help themselves