用python写一段代码实现这些功能:我的excel里第一列有一百家公司名,运行程序后,自动在指定网站上搜索第一列公司地址,输出地址在第二列
时间: 2023-03-14 15:32:44 浏览: 71
可以这样写:import requests
from bs4 import BeautifulSoup# 在第一列中获取100家公司的列表
companies = [c1, c2, c3, ... , c100]# 定义一个函数,用来获取每个公司的地址
def get_address(company):
url = 'http://www.example.com/search?q=' + company
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
address = soup.find('div', {'class': 'address'}).text
return address# 遍历每个公司,获取地址,并将结果写入excel的第二列
for company in companies:
address = get_address(company)
# 将地址写入第二列
excel.write(column=2, row=company, data=address)
相关问题
用python写一段代码实现这些功能:名为ABC的excel文件里第一列有一百家公司名,运行程序后,自动在指定网站上搜索第一列公司地址,输出地址在第二列
import requests
from bs4 import BeautifulSoup
import openpyxl# 打开文件
wb = openpyxl.load_workbook('ABC.xlsx')
# 选择表单
sheet = wb['Sheet1']
for i in range(1, sheet.max_row+1):
# 获取第一列内容
company_name = sheet.cell(row=i, column=1).value
# 拼接搜索链接
search_url = f'https://www.example.com/search?q={company_name}'
# 请求链接
r = requests.get(search_url)
# 解析页面
soup = BeautifulSoup(r.text, 'lxml')
# 获取公司地址
company_address = soup.select_one('div.company_address').get_text()
# 写入第二列
sheet.cell(row=i, column=2).value = company_address# 保存文件
wb.save('ABC.xlsx')
写一段python程序:文件夹G:\drought\data\data1\stationhh下保存着txt和xlsx文件,把每个表格第一行删除。
要完成这个任务,你可以使用Python的`pandas`库来处理`.xlsx`文件,以及内置的`open`函数来处理`.txt`文件。以下是一个简单的示例代码,它会遍历指定文件夹下的所有`.txt`和`.xlsx`文件,并对每个表格删除第一行。
```python
import os
import pandas as pd
from pandas import ExcelWriter
# 指定文件夹路径
folder_path = r'G:\drought\data\data1\stationhh'
# 获取文件夹下所有的.txt和.xlsx文件
files = [f for f in os.listdir(folder_path) if f.endswith(('.txt', '.xlsx'))]
# 遍历所有文件
for file in files:
file_path = os.path.join(folder_path, file)
if file.endswith('.xlsx'):
# 读取excel文件
df = pd.read_excel(file_path)
# 删除第一行
df = df.iloc[1:]
# 使用ExcelWriter写回文件
with ExcelWriter(file_path) as writer:
df.to_excel(writer, index=False)
elif file.endswith('.txt'):
# 打开并读取txt文件
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# 删除第一行
lines = lines[1:]
# 写回文件
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(lines)
print("处理完成。")
```
请注意,这段代码假设所有的`.xlsx`文件都是Excel表格,并且没有考虑工作表(sheet)的概念。如果你的`.xlsx`文件包含多个工作表,你需要对代码进行相应的修改。同样,对于`.txt`文件,这段代码假设它们是以UTF-8编码的文本文件。
在实际使用中,请确保已经安装了`pandas`库,可以通过运行`pip install pandas`来安装。