任何人都可以请帮助初学者。我编写了一些代码来收集网站的所有公司名称。它还打印出所有这些。但是,当我尝试将数据输入到 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 的屏幕截图):关于python - BS4 收集要列出的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852479/