Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中从BeautifulSoup数据创建元组列表?_Python_Web Scraping_Beautifulsoup_Data Science - Fatal编程技术网

如何在Python中从BeautifulSoup数据创建元组列表?

如何在Python中从BeautifulSoup数据创建元组列表?,python,web-scraping,beautifulsoup,data-science,Python,Web Scraping,Beautifulsoup,Data Science,我希望创建一个元组列表: 所需输出 d = [('Red','Apple'),('Green','Apple'),('Yellow','Banana'),('Blue','Berry')] HTML包含 <h2> <span class="head" id="Fruit">Apple</span> </h2> <ol> <li> <a href

我希望创建一个元组列表:

所需输出

d = [('Red','Apple'),('Green','Apple'),('Yellow','Banana'),('Blue','Berry')]
HTML包含

<h2>
    <span class="head" id="Fruit">Apple</span>
</h2>
<ol>
    <li>
        <a href = "/red" title="Red">Red</a>
        <a href = "/rot" title="Rot">Rot</a>
    </li>
    <li>
        <a href = "/green" title="Green">Green</a>
    </li>
</ol>
<h2>
    <span class="head" id="Banana">Banana</span>
</h2>
<ol>
    <li>
        <a href = "/yellow" title="Yellow">Yellow</a>
    </li>
</ol>
<h2>
    <span class="head" id="Berry">Berry</span>
</h2>
<ol>
    <li>
        <a href = "/blue" title="Blue">Blue</a>
    </li>
</ol>
<h2>
    <span class="head" id="Not">NotRequired</span>
</h2>
使用soup.findNext(class=“head”)

并在每个调用中构建元组


你这样做的方式,你无法区分,因为你不知道你有多少每种类型的水果在颜色列表方面,你可以使用
zip
function()

那么你的情况呢

desired_output = list(zip(box2, box1))

这还不够,
NotRequired
在这个列表中。为什么
('Red','Apple')
不是
('Red','Rot','Apple')
?因为我只想从所有
  • 标记中提取第一个标记。嘿,谢谢。我明白了。尽管如此,这对我来说还是有点困难,因为我是新来的。您可以帮助编写一些代码吗?在调用soup.findNext(class_u=“head”)之后,查找该头部(水果)中的所有颜色,并将每个颜色(水果、颜色名称)附加到列表中
    ['Apple','Banana','Berry','NotRequired']
    
    ['Red','Green','Yellow','Blue']
    
    >>> x = [1, 2, 3]
    >>> y = [4, 5, 6]
    >>> zipped = zip(x, y)
    >>> list(zipped)
    [(1, 4), (2, 5), (3, 6)]
    
    desired_output = list(zip(box2, box1))