【问题标题】:Exporting values from a Spreadsheet using Python for webscraping (BeautifulSoup4)使用 Python 从电子表格中导出值以进行网页抓取 (BeautifulSoup4)
【发布时间】:2016-08-08 00:56:10
【问题描述】:

A.我的目标: 使用 Python 从 Excel 电子表格中提取唯一的 OCPO ID,并使用这些 ID 在网络上抓取相应的公司名称和 NIN ID。 (注意:NIN 和 OCPO ID 对一家公司都是唯一的。

B.细节: 一世。使用 openpyxl 从 Excel 电子表格中提取 OCPO ID。 ii.在企业注册中心 (https://focus.kontur.ru/) 中逐一搜索 OCPO ID,并使用 BeautifulSoup4 查找相应的公司名称和公司 ID (NIN)。

示例:搜索 OCPO ID“00044428”会产生匹配的公司名称 ПАО "НК "РОСНЕФТЬ" 和对应的 NIN ID "7706107510"。

  1. 在 Excel 中保存公司名称和 NIN ID 的列表。

C.我的进步: 一世。我能够将 OCPO ID 列表从 Excel 提取到 Python。

# Pull the Packages
import openpyxl
import requests
import sys
from bs4 import BeautifulSoup

# Pull OCPO from the Spreadsheet
wb = openpyxl.load_workbook(r"C:\Users\ksong\Desktop\book1.xlsx")
sheet = wb.active
sheet.columns[0]
for cellobjc in sheet.columns[0]:
    print(cellobjc.value)

二。我可以搜索 OCPO ID 并让 Python 抓取匹配的公司名称和相应的公司 NIN ID。

# Part 1a: Pull the Website 
r = requests.get("https://focus.kontur.ru/search?query=" + "00044428")
r.encoding = "UTF-8"

# Part 1b: Pull the Content
c = r.content
soup = BeautifulSoup(c, "html.parser", from_encoding="UTF-8")

# Part 2a: Pull Company name
name = soup.find("a", attrs={'class':"js-subject-link"})
name_box = name.text.strip()
print(name_box)

D.帮助

我。您如何编写代码,以便将每个 OCPO ID 作为循环单独搜索,这样我就不会获得 OCPO ID 列表,而是获得搜索结果列表?换句话说,每个OCPO都被搜索并匹配到对应的Company Name和NIN ID。这个循环必须以######## ("https://focus.kontur.ru/search?query=" + "########") 的形式提供。

二。另外,我应该为 Python 使用什么代码将所有搜索结果保存在 Excel 电子表格中?

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup openpyxl


    【解决方案1】:

    1) 创建一个要写入的空工作簿:

    wb2 = Workbook()
    ws1 = wb2.active
    

    2) 将第二个框中的所有代码从第一个框放入 for 循环中。

    3) 将“00044428”改为str(cellobjc.value)

    4) 在每个循环结束时,将您的行附加到新工作表中:

    row = [cellobjc.value, date_box, other_variables]
    ws1.append(row)
    

    5) 循环结束后,保存文件

    wb2.save("results.xlsx")
    

    【讨论】:

      猜你喜欢
      • 2020-11-07
      • 1970-01-01
      • 2018-02-06
      • 2020-09-26
      • 1970-01-01
      • 2016-10-19
      • 2018-10-15
      • 2011-10-21
      • 1970-01-01
      相关资源
      最近更新 更多