【问题标题】:How do I modify code to parse multiple URL?如何修改代码以解析多个 URL?
【发布时间】:2023-03-11 19:44:01
【问题描述】:

我有这段代码可以获取页面中的所有子 URL。

如何通过此代码解析多个 URL?

from bs4 import BeautifulSoup
import requests

headers = {
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/91.0.4472.114 Safari/537.36'}
source = requests.get("https://www.oddsportal.com/soccer/england/efl-cup/results/", headers=headers)

soup = BeautifulSoup(source.text, 'html.parser')
main_div = soup.find("div", class_="main-menu2 main-menu-gray")
a_tag = main_div.find_all("a")
for i in a_tag:
    print(i['href'])

如何修改它以运行多个 URL

而我的 URL 列表如下:

df:

|    | URL                                                                 |
|----|---------------------------------------------------------------------|
|  0 | https://www.oddsportal.com/soccer/nigeria/npfl-pre-season/results/  |
|  1 | https://www.oddsportal.com/soccer/england/efl-cup/results/          |
|  2 | https://www.oddsportal.com/soccer/europe/guadiana-cup/results/      |
|  3 | https://www.oddsportal.com/soccer/world/kings-cup-thailand/results/ |
|  4 | https://www.oddsportal.com/soccer/poland/division-2-east/results/   |

我试过这样解析:

headers = {
    'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/91.0.4472.114 Safari/537.36'}
for url in df:
    source = requests.get(df['URL'], headers=headers)

    soup = BeautifulSoup(source.text, 'html.parser')
    main_div = soup.find("div", class_="main-menu2 main-menu-gray")
    a_tag = main_div.find_all("a")
    for i in a_tag:
        print(i['href'])

但是我收到了这个错误:

line 742, in get_adapter
    raise InvalidSchema("No connection adapters were found for {!r}".format(url))

如何修改相同的内容以解析多个 URL?

【问题讨论】:

  • 什么是df 对象?
  • 您可以创建一个函数,该函数接受 url 并遍历列表中调用该函数的每个 url。
  • @NizamMohamed 抱歉,我已更正正文以定义 df
  • @PyNoob_N 您正在迭代 df 数据框,您必须迭代列值 df['URL']
  • @MEdwin 我正在尝试这个question and its solution from here 但是我无法进步

标签: python web-scraping beautifulsoup


【解决方案1】:

改变

for url in df:
    source = requests.get(df['URL'], headers=headers)

for url in df['URL']:
    source = requests.get(url, headers=headers)

【讨论】:

  • 这行得通。我只是不像我想象的那样擅长开发人员逻辑哈哈。现在为这个菜鸟问题道歉。如何将print(i['href']) 保存到 csv?
  • @PyNoob_N 欢迎您,好吧,由于您是Stack Overflow! 社区的新手,我们仅限于为所提出的问题提供答案,因此在收到答案后从一个问题转移到另一个问题禁止在同一个帖子内。您必须为此创建另一个帖子。另外,请检查How to Ask 并提供minimal reproducible example
  • 你是对的!但是在问之前,我会自己尝试一下,如果我没有得到答案,我会问一个新问题。再次感谢您的指导。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 2020-12-20
相关资源
最近更新 更多