首页 > 解决方案 > 使用 Python Selenium 循环遍历 CSV 文件中的 URL 链接

问题描述

我在 csv 文件中有一组 URL,我想遍历这些链接并一次打开 CSV 中的每个链接。根据我的尝试,我遇到了几个不同的错误,但是我无法让浏览器打开链接。打印显示链接在那里。

当我运行我的代码时,我收到以下错误:

Traceback (most recent call last):
  File "/Users/Main/PycharmProjects/ScrapingBot/classpassgiit.py", line 26, in <module>
    open = browser.get(link_loop)
TypeError: Object of type bytes is not JSON serializable 

如果我遗漏了什么或者我做错了,有人可以帮我解决下面的代码。

我的代码:

import csv
from selenium import webdriver
from bs4 import BeautifulSoup as soup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as browser_wait
from selenium.webdriver.support import expected_conditions as EC
import requests

browser = webdriver.Chrome(executable_path=r'./chromedriver')

contents = []

with open('ClassPasslite.csv', 'rt') as cp_csv:
    cp_url = csv.reader(cp_csv)
    for row in cp_url:
        links = row[0]
        contents.append(links)

for link in contents:
    url_html = requests.get(links)

    for link_loop in url_html:

        print(contents)

        open = browser.get(link_loop)

标签: pythonseleniumcsvfor-loopselenium-webdriver

解决方案


由于您没有提供任何形式的变量中包含的内容,contents我将假设它是一个 url 字符串列表。

requests正如@cap.py 提到的那样,您同时使用and搞砸了selenium。当您执行 GET Web 请求时,目标服务器将向您发送文本响应。该文本可以是一些简单的文本,例如Hello world!,也可以是一些 html。但是此 html 代码将在您发送请求的计算机中进行解释。

这就是 selenium 对请求的意义:请求返回从目标(url)收集的文本,而 selenium 要求浏览器(例如 Chrome)收集文本,如果该文本是一些 html,则解释它以提供真正的可读性网页。此外,浏览器正在您的页面内运行 javascript,因此动态页面也可以正常工作。

最后,运行您的代码唯一需要做的就是这样做:

import csv
from selenium import webdriver
from bs4 import BeautifulSoup as soup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as browser_wait
from selenium.webdriver.support import expected_conditions as EC
import requests

browser = webdriver.Chrome(executable_path=r'./chromedriver')

contents = []

with open('ClassPasslite.csv', 'rt') as cp_csv:
    cp_url = csv.reader(cp_csv)
    for row in cp_url:
        links = row[0]
        contents.append(links)

#link should be something like "https://www.classpass.com/studios/forever-body-coaching-london?search-id=49534025882004019"
for link in contents:
    browser.get(link)
    # paste the code you have here

提示:不要忘记浏览器需要一些时间来加载页面。添加一些time.sleep(3)会对你有很大帮助。


推荐阅读