Python 写数据刮刀的问题
我必须做一个代码,以便从网站上抓取数据,然后为大学分析它们。 我的问题是,我编写这段代码是为了获得所有产品的一些数据,但当我运行它时,它只显示每个变量的单个响应。 你能帮我解决这个错误吗Python 写数据刮刀的问题,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我必须做一个代码,以便从网站上抓取数据,然后为大学分析它们。 我的问题是,我编写这段代码是为了获得所有产品的一些数据,但当我运行它时,它只显示每个变量的单个响应。 你能帮我解决这个错误吗 from bs4 import BeautifulSoup as soup import urllib from urllib.request import urlopen as uReq import requests myurl='https://boutique.orange.fr/mobile/ch
from bs4 import BeautifulSoup as soup
import urllib
from urllib.request import urlopen as uReq
import requests
myurl='https://boutique.orange.fr/mobile/choisir-un-mobile'
Uclient=uReq(myurl)
page=Uclient.read()
Uclient.close()
pagesoup=soup(page,'html.parser')
containers=pagesoup.findAll('div',{'class':'box-prod pointer'})
container=containers[0]
produit=container.img['alt']
price=container.findAll('span',{'class':'price'})
price2=container.findAll('div',{'class':'prix-seul'})
avis=container.footer.div.a.img['alt']
file="orange.csv"
f=open(file,'w')
headers='produit,prix avec abonnement, prix seul, avis\n'
f.write(headers)
for container in containers:
produit=container.img['alt']
price=container.findAll('span',{'class':'price'})
price2=container.findAll('div',{'class':'prix-seul'})
avis=container.footer.div.a.img['alt']
您可以使用不同的选择器。按指数将每个产品的两个价格分开。使用
join
和findall
提取特定于价格的信息
from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://boutique.orange.fr/mobile/choisir-un-mobile'
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
#print(len(soup.select('#resultat .box-prod.pointer')))
p = re.compile('[0-9,€]+')
altText= [item.get('alt').strip() for item in soup.select('#resultat .box-prod.pointer .lazy')]
titles = [item.text.strip().replace('\n', ' ') for item in soup.select('#resultat .box-prod.pointer .titre-produit')]
allPrices = [''.join(p.findall(item.text)) for item in soup.select('#resultat span.price')]
aPartirPrice = allPrices[0::2]
prixSeul = allPrices[1::2]
items = list(zip(titles, altText, aPartirPrice, prixSeul))
df = pd.DataFrame(items,columns=['title', 'altText', 'aPartirPrice', 'prixSeul'])
df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8',index = False )
转置为:
df = df.T
谢谢你,我设法修改了我的代码以使其正常工作,但我还有最后一个问题:当我将其放入csv文件时,它会将每个产品的所有数据放在一列中,而不是在价格、评论栏中……尝试使用df=df.TDId回答你的原始问题吗?