使用 Python 从电子表格中导出值进行网络抓取

问题描述 投票:0回答:1

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”

iii.在 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)

ii.我可以搜索 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都会被搜索并与相应的公司名称和NIN ID相匹配。该循环必须作为

######## ("https://focus.kontur.ru/search?query=" + "########")
进行馈送。

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

python python-3.x web-scraping beautifulsoup openpyxl
1个回答
0
投票

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")
© www.soinside.com 2019 - 2024. All rights reserved.