抓取类元素

时间:2021-03-19 13:17:21

标签: python web-scraping beautifulsoup

我想在 class="cms-no-route cms-noroute-index page-layout-1column" 中抓取 <body data-containr="body" class="cms-no-route cms-noroute-index page-layout-1column"> 并将其保存在一个 txt 文件中,但是由于某种原因,当我运行脚本时没有任何反应。

def get():
 source = requests.get("https://shop.adidas.ae/en/yeezy-boost-350-v2-ash-pearl/GY7658.html", headers=randomheaders.LoadHeader()).text
 soup = BeautifulSoup(source, 'lxml')
 x = soup.find_all('body', datacontainer_="body")
 url = x.get('class')
 filename = "adidaslive.txt"
 with open(filename, "r") as rf:
   with open(filename, "a") as af:
     if url not in rf:
       print(url)
       af.write("\n" + url)
     else:
      print("nothing")

1 个答案:

答案 0 :(得分:0)

def get():
    source = ...

你需要正确缩进你的代码

x = soup.find_all('body', datacontainer_="body")

x 这里是一个只有一个元素的列表,因为在你的 html 源代码中只有一个“body”标签。