python - BS4 收集要列出的行

标签 python excel beautifulsoup

任何人都可以请帮助初学者。我编写了一些代码来收集网站的所有公司名称。它还打印出所有这些。但是,当我尝试将数据输入到 Excel 文件中时,它只输入最后的公司名称。
继承人的代码:如果有人可以帮助我会很感激它。

import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook



print('Welcome!')
search = input('Search for what? ')

URL = 'https://www.merinfo.se/search?ap=1&emp=0%3A100&rev=0%3A100000&d=c&who=' + search + '&where=&bf=1'
headers = {
    'User Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'
}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')





for i in soup.find_all('h2', class_='name'):
    print(i.get_text())




workbook = Workbook()
sheet = workbook.active

sheet["A2"] = i.get_text()
workbook.save(filename="foretagen.xlsx")

最佳答案

您可以使用 sheet.append()将行添加到 excel 文件。
例如:

import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook


print('Welcome!')
search = input('Search for what? ')

URL = 'https://www.merinfo.se/search?ap=1&emp=0%3A100&rev=0%3A100000&d=c&who=' + search + '&where=&bf=1'
headers = {'User Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'}

page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')

workbook = Workbook()
sheet = workbook.active

for i in soup.find_all('h2', class_='name'):
    txt = i.get_text(strip=True)
    print(txt)
    sheet.append([txt])

workbook.save(filename="foretagen.xlsx")
打印:
Welcome!
Search for what? tree
Tree Logistics AB
Sushi tree AB
Beech Tree AB
BIN TREE AB
TALENT TREE AB
Juniper Tree AB
Hope Tree AB
Dead tree group AB
The Tree Karsikko AB
Willow Tree Consulting AB
Learning Tree International Aktiebolag
Palm Tree Tunes AB
Tree of Pets AB
nordic tree care AB
For Tree i Rossön Aktiebolag
Trädkompaniet Voice Of Tree Care AB
Omsorgshuset Red Tree Care Center AB
Global Tree Care i Sundbyberg AB
Three Rock AB
Three Gates AB
并写入 excel 文件(来自 LibreOffice 的屏幕截图):
enter image description here

关于python - BS4 收集要列出的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852479/

相关文章:

python - 在Python中解析数据集中的特定列

python - 基于用户输入在 Python 中创建加权有向图

excel - pretty-print Excel 公式?

excel - 如何在不使用 VBA 的情况下在 Excel 中执行反向字符串搜索?

Python BeautifulSoup 根据id提取标题

javascript - 使用 BeautifulSoup 从 Javascript 中提取文本以获得关注者数量

python将ipv6转换为整数

python - 遍历整个区间的聪明方法

vba - 在 VBA 中使用函数内部的数组

python - 使用 BeautifulSoup 抓取带有下拉列表的表格内容