首页 > 解决方案 > 如何在 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-3.xgspread

解决方案


我在另一个问题中找到了答案: 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)

推荐阅读