python-3.x - 如何在 Python3 中使用 gspread 在相应 URL 旁边的左侧单元格中打印 xpath 的值?
问题描述
我的目的是从一系列 URL 中抓取 xpath 的值,这些 URL 位于 Google 表格的第四列中,并在 URL 左侧的单元格中打印该值。
到目前为止,我有以下内容,但是当我运行它时,它会打印所有 URL 的 adGroupStatus 列表的最后一个值,而不是每个相应 URL 的正确值。
任何人都可以提供解决方案吗?
import requests
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from lxml import html
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sh = client.open('example_sheet_name')
worksheet = sh.get_worksheet(0)
# the column (4th) with our URLs
url_list = worksheet.col_values(4)
# where we want our xpath values to print to
cell_list = worksheet.range('C1:C5')
def grab_xpathtext(urls, cell_range):
# do the below for each url in the spreadsheet column 4:
for url in urls:
r = requests.get(url)
tree = html.fromstring(r.content)
adGroupStatus = tree.xpath('//*[@id="m_count"]/text()')
# below prints each value to the cmd line on a new line as expected
print(adGroupStatus[0])
for cell in cell_range:
# below prints the last value instead of each corresponding value
cell.value = adGroupStatus[0]
worksheet.update_cells(cell_range)
grab_xpathtext(url_list, cell_list)
我希望输出类似于:
| 位置 1 | 描述 | 1 | 网址 1 |
| 位置 2 | 描述 | 2 | 网址 2 |
| 位置 3 | 描述 | 3 | 网址 3 |
| 位置 4 | 描述 | 4 | 网址 4 |
| 位置 5 | 描述 | 5 | 网址 5 |
...但相反,我得到了这个:
| 位置 1 | 描述 | 5 | 网址 1 |
| 位置 2 | 描述 | 5 | 网址 2 |
| 位置 3 | 描述 | 5 | 网址 3 |
| 位置 4 | 描述 | 5 | 网址 4 |
| 位置 5 | 描述 | 5 | 网址 5 |
解决方案
我在另一个问题中找到了答案: Python/gspread - 如何一次更新多个具有不同值的单元格?
实现为:
url_list = worksheet.col_values(4)
cell_list = worksheet.range('C1:C5')
def grab_xpathtext(urls, cell_range):
statuses = []
for url in urls:
r = requests.get(url)
tree = html.fromstring(r.content)
adGroupStatus = tree.xpath('//*[@id="m_count"]/text()')
statuses.append(adGroupStatus[0])
print(statuses)
for cell in cell_range:
for i, val in enumerate(statuses):
cell_range[i].value = val
worksheet.update_cells(cell_range)
grab_xpathtext(url_list, cell_list)
推荐阅读
- django - "AUTH_USER_MODEL 指的是尚未安装的模型 '%s'" % settings.AUTH_USER_MODEL 尚未安装
- netlogo - 海龟自己的变量到 NetLogo 上的全局变量
- java - 尝试使用 .replace() 替换使用 XPATH java 提取的 XML 依赖项
- c++ - 用于 C++ Builder 64 位的 OpenCV CMAKE 库扩展
- android - 实时绘制折线图
- javascript - 在扩展之前显示为空的数组时如何访问我的数组
- python-3.x - 如何在数据集上应用 PCA 并打印相关特征
- python - 在 Python 中清除调用堆栈
- node.js - NPM 安装不适用于 Node V 16.0.0
- python - 无法从 DJango 中的数据库中过滤