【问题标题】:Method to Scrape a python list of multiple URLs抓取多个 URL 的 python 列表的方法
【发布时间】:2021-12-23 19:39:30
【问题描述】:

我为我需要的 URL 抓取了维基百科页面,并将其附加到 python 中的一个空列表中。 我现在需要抓取列表中的每个 URL 以获取特定信息,例如日期、坐标等。

鉴于 HTML 代码的结构,父/子父结构,很多信息不能单独通过标签链接。或者可以吗?请参阅以下链接中的事实框:https://en.wikipedia.org/wiki/1987_Maryland_train_collision。 我的目标是抓取这些事实框,因为它们中的大多数都包含一个。

我了解您可以使用条件语句从一组数据中声明特定数据,并使用相同的 HTML 标记。但是,我不确定如何处理它。

到目前为止,我有以下内容:

list_of_urls = #my list of urls to be scraped


for i in list_of_urls:
        
        soup = BeautifulSoup(text, features="lxml")
        
        for item in soup.findAll('td',attrs={'class':'infobox-label'}):
            
            if item.find('td', attrs={'class':'infobox-data'})  == "date":
                print(item.find)
    
                date_info = item.get("infobox-data")
                print(date_info)

                #do something more..    

Any thoughts on the above?
Thank you for your time.

EDIT: Solved by applying Rusticus methods.. 

【问题讨论】:

    标签: python list url web-scraping


    【解决方案1】:

    您正在检查的结构如下所示:

    <tr>
      <th scope="row" class="infobox-label" style="white-space:nowrap;padding-right:0.65em;">Date</th>
      <td class="infobox-data" style="line-height:1.3em;">January 4, 1987 <br>1:30 PM</td>
    </tr>
    • 请注意,“infobox-label”位于 TH 标签而非 TD 标签中。
    • item.find 是一种方法,您可能打算使用“print(item)”
    • 找到 TH 标签后,您需要移动到 TD 标签以获取值。有几种方法可以做到这一点,我认为最简单的是引用“item.parent.td”

    也许你正在寻找这样的东西:

        for item in soup.findAll('th',attrs={'class':'infobox-label'}):
            
            if item.text  == "Date":
                print(item)
    
                date_info = item.parent.td.text
                print(date_info)
    

    或者只是:

    soup.select_one('.infobox').find('th', text="Date").parent.td.text.strip()
    

    对于坐标:

    soup.select_one('.infobox').find('th', text="Coordinates").parent.td.select_one('.geo-dec').text.strip()
    

    【讨论】:

    • 非常感谢!它适用于我需要的所有东西,但坐标。你知道为什么吗?有关我收到的输出,请参阅我对此线程的“答案”。如果你没有时间,足够公平。再次感谢您!
    • 添加了坐标选择器
    • 它给出了一个干净的坐标数量,但奇怪的是,对于每个 URL,它会在任何地方重复它们 5 到 10 次。最后一个我通过解决:32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889 °N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W 32.31889°N 88.97222°W...有什么想法吗?否则,删除重复项应该很容易。
    • 您确定您使用的是“select_one”而不是“select”吗?
    • 不是这样的。混合了其他数据的代码的某些部分,特别是坐标。现在一切都好,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2020-11-08
    • 2011-07-16
    • 2017-07-07
    相关资源
    最近更新 更多