Python 如何使用CSS获取信息?

Python 如何使用CSS获取信息?,python,html,css,scrapy,Python,Html,Css,Scrapy,我尝试在scrapy shell中使用CSS:response.CSS('#fq9.answer options td::text').get() 响应:'\xa0'。如何删除它 因为基本上是一个奇特的空白,所以可以使用.strip() 如果没有适合CSS选择器的内容,您将获得无作为您的公司名称。如果像.get().strip()那样添加条带,则会导致错误。考虑检查 No.: def profile(self, response): out = response.css('#fq9

我尝试在scrapy shell中使用CSS:
response.CSS('#fq9.answer options td::text').get()

响应:
'\xa0'
。如何删除它


  • 因为基本上是一个奇特的空白,所以可以使用
    .strip()
  • 如果没有适合CSS选择器的内容,您将获得
    作为您的
    公司名称
    。如果像
    .get().strip()
    那样添加条带,则会导致错误。考虑检查<代码> No.<代码>:

    def profile(self, response):
        out = response.css('#fq9 .answer-options td::text').get()
        if out is not None:
            yield {'Company Name': out.strip()}
    
编辑:您似乎有多个具有不同
#fq
索引的域。您可以在解析之前对名称和索引进行分组,这将允许您使用循环:

def profile(self, response):
    fields = {
        'field1': 1,
        'field3': 3,
        'Company Name': 9
    }
    for name in fields:
        value = response.css('#fq{} .answer-options td::text'.format(fields[name])).get()
        if value is not None:
            yield {name: value.strip()}

您可以尝试
response.replace('\xa0','')
?TypeError:uu init_uuu()为参数'url'获取了多个值,我的意思是
var=response.css('\fq9.answer options td::text')。get()
然后是var.replace('\xa0',''),那么我可以使用吗response.css('#fq9.answer options td::text').get().replace('\xa0','')What if response.css('#fq9.answer options td::text').get()为None,则会出现错误NoneType没有方法replace,因此最好单独执行。如何一次检查多个字段?用于?“def profile(self,response):Company_Name=response.css(“#fq9.answer options td::text”).get()如果Company_Name不是None:Company_Name=Company_Name.strip()麻醉师_Name=response.css(“#fq14.answer options td::text”).get()如果麻醉师\u Name不是None:Anesthesiologists\u Name=Anesthesiologists\u Name.strip()产生{“公司名称”:公司名称,“麻醉师名称”:Anesthesiologists\u Name,}似乎您有一个索引:fq id和编号。首先生成css选择器,然后对所有内容使用for循环。我用多个字段的示例更新了答案