【问题标题】:Scraping multiple URLs using BeautifulSoup使用 BeautifulSoup 抓取多个 URL
【发布时间】:2020-09-18 14:46:14
【问题描述】:

我正在尝试抓取一个网站,但是我无法完成代码,以便我可以一次插入多个 URL。目前,该代码一次只能使用一个 URL,

目前的代码是:

import requests
from bs4 import BeautifulSoup
import lxml
import pandas as pd

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
try:
    html = urlopen("http://google.com")
except HTTPError as e:
    print(e)
except URLError:
    print("error")
else:
    res = BeautifulSoup(html.read(),"html5lib")
    tags = res.findAll("div", {"itemtype": "http://schema.org/LocalBusiness"})
    title = res.title.text
    print(title)
    for tag in tags:
      print(tag)

有人可以帮我修改一下,以便我可以插入这样的东西吗?

html = urlopen ("url1, url2, url3") 

【问题讨论】:

  • 你问的没有意义。 BeautifulSoup 不是这样工作的。为什么不使用相同的代码一次处理一个 URL,如果您希望同时处理这三个 URL 会起作用? - 或者您是否期望发生比单独处理每个 URL 时更复杂的结果?

标签: python beautifulsoup html5lib


【解决方案1】:

将代码的可重复部分包装在一个函数中并使用一个列表:

def urlhelper(x):
    for ele in x:
        try:
            html = urlopen(ele)
        except HTTPError as e:
            print(e)
        except URLError:
            print("error")
        else:
            res = BeautifulSoup(html.read(),"html5lib")
            tags = res.findAll("div", {"itemtype": "http://schema.org/LocalBusiness"})
            title = res.title.text
            print(title)
            for tag in tags:
            print(tag)

用 urlhelper(["url1","url2","etc"]) 调用这个函数

这里要理解的关键概念是“for”,它告诉 python 遍历列表中的每个元素。

我建议阅读迭代器和列表以获取更多信息:

https://www.w3schools.com/python/python_lists.asp

https://www.w3schools.com/python/python_iterators.asp

【讨论】:

  • 非常感谢!!
【解决方案2】:

您可以创建一个 url 列表并使用 for 循环遍历它,如下所示:

import requests
from bs4 import BeautifulSoup
import lxml
import pandas as pd

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup

urlList = ["url1", "url2", "url3", "url4"]

for url in urlList:
    try:
        html = urlopen(url)
    except HTTPError as e:
        print(e)
    except URLError:
        print("error")
    else:
        res = BeautifulSoup(html.read(),"html5lib")
        tags = res.findAll("div", {"itemtype": "http://schema.org/LocalBusiness"})
        title = res.title.text
        print(title)
        for tag in tags:
          print(tag)

【讨论】:

  • 感谢古文!完美运行
  • @SergioCuritiba:如果它“完美运行”,请将答案标记为已接受。或者,如果您认为这是最好的答案,请接受另一个答案。
猜你喜欢
  • 2021-09-01
  • 1970-01-01
  • 2018-04-15
  • 2020-06-27
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多