【问题标题】:python web scraping,web parserpython网页抓取,网页解析器
【发布时间】:2021-02-28 22:27:56
【问题描述】:

我刚开始学习 python,但我在抓取时遇到了问题。 代码可以正常工作,但是当我抓取时,却只得到空列表 []。 我做错了什么? 我找不到同样的问题,感谢您的宝贵时间!

`import requests
from bs4 import BeautifulSoup as bs4

headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

}

url = "https://www.worldometers.info/geography/alphabetical-list-of-countries/"
session = requests.session()


try:
    req = session.get(url, headers=headers)
    if req.status_code == 200:
        soup =  bs4(req.content, "html.parser")
        divs = soup.find_all("div", attrs={"style" : "font-weight"})
        name = soup.find_all()
        print(divs)
except Exception:
    print("ERORR IN URL ADRESS")`

【问题讨论】:

  • 是因为没有元素满足你传递的属性。您要提取哪些元素?
  • 我要打印所有国家/地区。
  • 做一些检查,确保你想要的不是由 JS 生成的

标签: python list web-scraping request html-parsing


【解决方案1】:

您可以获取类table-condensed 的表并找到您需要的数据。请检查以下代码:

import requests
from bs4 import BeautifulSoup

headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

}

url = "https://www.worldometers.info/geography/alphabetical-list-of-countries/"
session = requests.session()


try:
    req = session.get(url, headers=headers)
    if req.status_code == 200:
        soup =  BeautifulSoup(req.content, "html.parser")
        countries = soup.find("table", {"class": "table-condensed"}).find("tbody").findAll("tr")
        for country in countries:
            print(country.findAll("td")[1].text)
            
except Exception:
    print("ERORR IN URL ADRESS")

【讨论】:

  • 如果对您有帮助,请批准答案:)
  • 抱歉这么愚蠢的问题,但我怎么能批准?
  • 答案左侧有一个勾号图标
猜你喜欢
  • 2017-03-24
  • 2020-06-18
  • 2021-01-12
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多