python - 在python中使用硒循环csv文件中的链接
问题描述
我正在尝试打开一个 .csv 文件,并使用 selenium 打开 .csv 文件中的链接,并循环浏览 .csv 文件中的链接。我是 Selenium 的新手。我可以很容易地用漂亮的汤做到这一点。请你指导我正确的方向。
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import csv
import requests
contents =[]
filename = 'link_business_filter.csv'
def copy_json():
with open('vendors_info_bangkok.json',"a") as wt:
for x in script3:
wt.write(x)
wt.close()
return
with open(filename,'rt') as f:
data = csv.reader(f)
for row in data:
links = row[0]
contents.append(links)
for link in contents:
url_html = requests.get(link)
browser = webdriver.Chrome('chromedriver')
for link_loop in url_html:
open = browser.get(link_loop)
source = browser.page_source
data = bs(source,"html.parser")
body = data.find('body')
script = body
x_path = '//*[@id="react-root"]/section/main/div'
script2 = browser.find_element_by_xpath(x_path)
script3 = script2.text
print(script3)
copy_json()
解决方案
首先安装硒:
pip install selenium
然后根据您的
os
安装chromediver
,然后通过转到保存驱动程序的文件夹并打开终端并输入来测试它chromedriver
,如果没有错误则它可以工作。然后在您的代码中,您需要
executable_path
提供chromdriver
在你的代码中:
....code...
for link in contents:
url_html = requests.get(link)
path to chromdriver = 'C:/Users/chromedriver.exe' #<-- you can keep this file anywhere you wish
browser = webdriver.Chrome(executable_path= 'path_to_chromdriver') #<-- you can also give the path directly here
for link_loop in url_html:
...code...
推荐阅读
- flutter - 如何获取 Pageview 中的页数以用于 Flutter 中的行指示器?
- swift - 尝试将结构应用于可折叠tableview Swift的多维日期数组
- powerbi - power bi 中的 Sumproduct 公式
- html - Angular 自定义复杂路由器转换
- sql - SQL Server 性能不佳,使用 UPPER() 有很多 OR 和重复条件
- html - 是否可以通过输入一次 URL 来创建链接?
- sql - 在 SQL 中使用 HAVING 子句
- mysql - 在 Node.js MySQL 中等待查询
- flutter - 在flutter web中直接使用url参数导航到一个网页
- java - 运行时 Maven 上的 NoClassDefFoundError