如何将文本文件中的URLS存储在数组中以使用Selenium浏览器访问?

我已经尝试过了:

def ad_open_file(ad_chrome):
    ad_url_list = []
    for line in ad_url_list:
        ad_url_list.append(line)

所以我希望数组看起来像这样:

ad_url_list = ['https://www.link.org','https://www.link.org']

在那之后,我想使用硒浏览器访问每个URL,并且在它们之间使用time.sleep(5)。是通过for循环完成的吗?

有人可以帮我吗?

wuyangsunyu 回答:如何将文本文件中的URLS存储在数组中以使用Selenium浏览器访问?

要使用Selenium浏览器访问每个URL并在两次访问之间休眠,您可以尝试以下操作:

from selenium import webdriver
from time import sleep

# first get lines from the file -- assuming ad_chrome is your file path?
with open(ad_chrome) as f:

    # lines is a list containing each line in the file,as a list item
    lines = f.readlines()

    # start the webdriver
    driver=webdriver.Chrome()

    # now loop through lines and visit each URL
    for url in lines:

        # visit the URL
        driver.get(url.rstrip()) # call rstrip() to remove all trailing whitespace

        # wait 5 seconds
        sleep(5)

希望这可以帮助您入门。我们不需要将文件内容保存到数组中,因为我们可以遍历文件中的每一行,因此将文件行放入数组中有点多余。

我们在每一行调用rstrip(),以删除文件中可能存在的尾随空格和换行符。

此代码假定您的文件类似于:

www.someurl.com
www.anotherurl.com
www.google.com

等等。

本文链接:https://www.f2er.com/3070958.html

大家都在问