繁体   English   中英

Web 用 Python 抓取(beautifulsoup)

[英]Web scraping with Python(beautifulsoup)

我有一个错误。 我需要将我的 output 写入 csv 文件。 但我不能那样做,如果你有时间请帮忙分页。 错误代码:TabError:缩进中制表符和空格的使用不一致在此处输入图像描述

import requests
import csv
from bs4 import BeautifulSoup as bs
from lxml import etree

url = 'https://bina.az/baki/alqi-satqi/menziller/yeni-tikili/1-otaqli'
r = requests.get(url)
soup = bs(r.content,"lxml")
container = soup.find_all("div",class_="items_list")[-1]
items = container.find_all("div",class_="items-i")

 
file = open('menziller.csv', 'w',newline='')
writer = csv.writer(file)
writer.writerow(["price", "location", "info"])



for element in items:
    price = element.find("div",class_="price").text
    location = element.find("div",class_="location").text
    info  = " ".join([x.text for x in element.find("ul",class_="name").find_all("li")])
    writer.writerow([price, location, info])

file.close()

当文件包含空格和制表符的混合时,会发生TabError: inconsistent use of tabs and spaces in indentation错误。 我怀疑第 20-23 行之一使用制表符,而其他行之一使用空格。

Python 不允许空格和制表符之间的混合。 这是因为相当于一个制表符的空格数因系统而异,范围为 2、4 或 8 个空格。 生成的程序会有所不同,具体取决于 Python 如何将这些制表符转换回空格,这会导致非常混乱的错误。

相反,Python 会抛出一个异常,告诉您要么专门使用制表符,要么专门使用空格。 习惯上使用空格。

这不是有效的 python 语法。 请使用 VSCode 之类的代码编辑器来编写代码。

参考: https://code.visualstudio.com/

你也可以使用这个: https://www.tutorialspoint.com/online_python_formatter.htm


#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import csv
from bs4 import BeautifulSoup as bs
from lxml import etree

url = 'https://bina.az/baki/alqi-satqi/menziller/yeni-tikili/1-otaqli'
r = requests.get(url)
soup = bs(r.content, 'lxml')
container = soup.find_all('div', class_='items_list')[-1]
items = container.find_all('div', class_='items-i')

file = open('menziller.csv', 'w', newline='')
writer = csv.writer(file)
writer.writerow(['price', 'location', 'info'])

for element in items:
    price = element.find('div', class_='price').text
    location = element.find('div', class_='location').text
    info = ' '.join([x.text for x in element.find('ul', class_='name'
                    ).find_all('li')])
    writer.writerow([price, location, info])

file.close()

干得好!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM