python - 使用 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)
解决方案
由于您没有提供任何形式的变量中包含的内容,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)
会对你有很大帮助。
推荐阅读
- git - git客户端:如何为http使用不同的本地接口(或绑定地址)
- javascript - const signInWithGoogle 没有在反应中导出,因此屏幕变白
- javascript - 我不断收到此错误:无法修改已提交的 WriteBatch
- api - 例外:无效参数 - API 天气当前数据拉取
- python - 在具有 Lambda 函数的 dynamodb 表中将 python 用于 put_item
- c++ - 使用 SIMD 的种子随机均匀浮点生成器?
- mongodb - Mongoose:为找不到文档定义 404 状态不起作用
- javascript - 从对象数组中仅获取一个字段值
- python - 如何使用 Beautifulsoup 从标签之间移动的表格中提取文本
- winapi - 如何在 ATL exe 中为多个对话框发送消息