from bs4 import BeautifulSoup as soup
from urllib.request import urlopen as uReq
my_url = 'https://www.flipkart.com/search?q=iphone+12&sid=tyy%2C4io&as=on&as-show=on&otracker=AS_QueryStore_OrganicAutoSuggest_1_6_na_na_na&otracker1=AS_QueryStore_OrganicAutoSuggest_1_6_na_na_na&as-pos=1&as-type=HISTORY&suggestionId=iphone+12%7CMobiles&requestId=71ed5a8e-4348-4fef-9af8-43b7be8c4d83'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
containers = page_soup.findAll("div", {"class": "_13oc-S"})
#print(len(containers)) "will tell number of products on the respected page"
#print(len(containers))
#print(soup.prettify(containers[0])) "will bring the page in the organised manner"
#print(soup.prettify(containers[0]))
container=containers[0]
#print(container.div.img["alt"]) "will display the name of the respected product"
#print(container.div.img["alt"])
#price=container.findAll("div",{"class":"col col-5-12 nlI3QM"}) "will tell the price of the respect project"
price=container.findAll("div",{"class":"col col-5-12 nlI3QM"})
#print(price[0].text)
ratings=container.findAll("div",{"class":"gUuXy-"})
#print(ratings[0].text)
#Making a file
filename = "products.csv"
f= open(filename, "w")
#Naming the headers
headers = "Product_Name,Pricing,Ratings\n"
f.write(headers)
for container in containers:
product_name = container.div.img["alt"]
price_container = container.findAll("div", {"class": "col col-5-12 nlI3QM"})
price = price_container[0].text.strip()
rating_container = container.findAll("div", {"class":"gUuXy-"})
rating = rating_container[0].text
#print("product_name:" + product_name)
#print("price:" + price)
#print("ratings:" + rating)
#string parsing
trim_price = ''.join(price.split(','))
rm_rupee = trim_price.split("₹")
add_rs_price = "Rs." + rm_rupee[0]
split_price = add_rs_price.split('E')
final_price = split_price[0]
split_rating = rating.split(" ")
final_rating = split_rating[0]
print(product_name.replace(",", "|") + "," + final_price + "," + final_rating + "\n")
f.write(product_name.replace(",", "|") + "," + final_price + "," + final_rating + "\n")
f.close()
f.write(product_name.replace(",", "|") + "," + final_price + "," + final_rating + "\n")
Имея синтаксическую ошибку в этой конкретной строке, Я хочу создать файл .CSV, но продукты не входят в уважаемый файл. Синтаксическая ошибка -: Произошло исключение: UnicodeEncodeError Кодек 'charmap' не может кодировать символ '9' в позиции 35: символы сопоставляются с Файл "D:\Visual Code Folder\Python\Scraping_Flipkart.py", строка 61, в f.write(product_name.replace(",", "|") + "," + final_price + "," + final_rating + "\n")
Предоставьте ожидаемый минимальный воспроизводимый пример. Нам нужен минимум кода, а не дамп программы в 50 строк. Включите все сообщение об ошибке.
Внешние ссылки и изображения текста не допускаются; нам нужно, чтобы ваш вопрос был автономным, в соответствии с целью этого сайта. Пожалуйста, повторите по теме и как спросить из ознакомительного тура.
Замените это
f= open(filename, "w")
с этим
import io
f = io.open(filename, "w", encoding = "utf-8")
Использование io обеспечивает обратную совместимость с Python 2.
Если вам нужна только поддержка Python 3, вместо этого вы можете использовать встроенную функцию открытия:
with open(fname, "w", encoding = "utf-8") as f:
f.write(html)
Как это собирается исправить SyntaxError?
При открытии файла вы должны кодировать его с помощью encoding = "utf-8". Для платформы Linux этого делать не нужно, но для платформы Windows вы должны это использовать.
Покажите нам полное исходное сообщение об ошибке!