在 csv 文件中打印信息

print info in a csv file

我有一个程序可以打印来自网站的信息,但我想将此信息放入 csv 或 excel 文件中。这就是我所做的:

import requests
from bs4 import BeautifulSoup
import re
import xlsxwriter


workbook  = xlsxwriter.Workbook('nossarede.xlsx')
worksheet = workbook.add_worksheet()

request = requests.get("http://www.drogariasnossarede.com.br/nossas-lojas")
soup = BeautifulSoup(request.content, 'html.parser')
data = soup.find_all("div", class_='item')

for container in data:
  Pharmacyname = container.find_all("h3")
  Pharmacyadd  = container.find_all("p")
  for pharmacy in Pharmacyname:
      print(pharmacy.text)
      for add in Pharmacyadd:
          print(add.text)
      print('')

直到这里完美为止,它以我想要的方式完美打印。然后我试了这个:

    import csv
    with open('names.csv', 'wb') as ofile:
        writer = csv.writer(ofile)
        for container in data:
            Pharmacyname = container.find_all("h3")
            Pharmacyadd  = container.find_all("p")
            for pharmacy in Pharmacyname:
                for add in Pharmacyadd:
                    writer.writerow((pharmacy.text[0], add.text[1]))

但是它不起作用。 它显示了这个:

TypeError: a bytes-like object is required, not 'str'

我该怎么做?? 谢谢!

您正在使用 wb 以字节模式打开文件。

只要改变这个:

with open('names.csv', 'wb') as ofile:

对于

with open('names.csv', 'w') as ofile:

还有一件事。你的 writerow 是错误的。您只获得字符串的第一个字符。

改变这个:

 writer.writerow((pharmacy.text[0], add.text[0]))

用于:

writer.writerow((pharmacy.text, add.text))

变化:

with open('names.csv', 'wb') as ofile:

这是写字节模式,到:

with open('names.csv', 'w') as ofile:

完整代码:

import requests
from bs4 import BeautifulSoup
import re
import xlsxwriter

request = requests.get("http://www.drogariasnossarede.com.br/nossas-lojas")
soup = BeautifulSoup(request.content, 'html.parser')
data = soup.find_all("div", class_='item')

import csv
with open('names.csv', 'w', newline='', encoding="utf-8") as ofile:
    writer = csv.writer(ofile)
    for container in data:
        Pharmacyname = container.find_all("h3")
        Pharmacyadd  = container.find_all("p")
        for pharmacy in Pharmacyname:
            for add in Pharmacyadd:
                writer.writerow((pharmacy.text, add.text))