I am scraping a classifieds' site and each page has 15 listings for the search results. Most vehicle listings will have class=price for the price. However, there are some listings that omit a price which means my array of 15 can be missing values and that's a problem when I later loop through them to display the listings on my site. So how can I ensure that each array value is populated? Here is an example of the HTML from the site that I'm scraping:
我正在抓取一个分类广告的网站,每个页面都有15个搜索结果列表。大多数车辆列表的价格都是class=price。然而,有些列表省略了价格,这意味着我的15个数组可能会丢失值,当我稍后循环查看它们以在我的网站上显示列表时,这是一个问题。那么,如何确保填充每个数组值呢?以下是我正在抓取的网站中的HTML示例:
<div class="search-results">
<a class="inner">
<div class="desc">Vehicle 1</div>
<div class="desc">Vehicle 2</div>
<div class="desc">Vehicle 3</div>
<div class="desc">Vehicle 4</div><div class="price">$30,000</div>
<div class="desc">Vehicle 5</div>
...
<div class="desc">Vehicle 15</div>
</a>
</div>
Here is my code which works if there are prices for each listing, but fails if any are missing:
以下是我的代码,如果每个列表都有价格,它会起作用,但如果缺少价格,它就会失败:
foreach($html->find('div[class="search-results"] a[class=inner] div[class=price]') as $a) {
$car_price[] = $a->plaintext;
}
This code only returns one array value in this example and it's not even in the 4th position of the array because it's the only value in the array. So how can I ensure that all 15 array elements have a value, even if the price is null? My thought was to create a null value if it's missing but I'm not sure how to do that. Thank you!
在本例中,此代码只返回一个数组值,它甚至不在数组的第4个位置,因为它是数组中唯一的值。那么,即使价格为空,我如何确保所有15个数组元素都有一个值呢?我的想法是,如果缺少空值,就创建一个空值,但我不知道该怎么做。非常感谢。
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!