React Native如何用Fetch结合Cheerio抓取并展示目标页面商品
How to Parse and Display Product Data from a Web Page in React Native Using Cheerio
Hey there! I see you’ve already got the raw HTML fetched, but need help extracting those product listings with Cheerio. Let’s fix that up so you can display actual product info instead of the full HTML markup.
Step 1: Install Cheerio
First, add Cheerio to your project. Run this in your terminal:
npm install cheerio # or yarn add cheerio
Step 2: Update Your Component Code
Here’s the revised component that uses Cheerio to parse product data and displays it with a FlatList (way better for list content than a single Text component):
import React from 'react'; import { View, Text, FlatList, Image, StyleSheet } from 'react-native'; import cheerio from 'cheerio'; // Import Cheerio class DealsPage extends React.Component { state = { products: [], isLoading: true }; fetchData = async () => { try { const response = await fetch('https://www.herba-market.co.rs/kategorija/proizvodi-na-akciji/'); const html = await response.text(); // Load the HTML into Cheerio for parsing const $ = cheerio.load(html); // Extract product data from elements with class 'product' const productList = []; $('.product').each((index, element) => { // Pull out key product details - adjust selectors if needed based on the page's actual structure const title = $(element).find('.product-title').text().trim(); const price = $(element).find('.price').text().trim(); const imageUrl = $(element).find('img').attr('src'); const productUrl = $(element).find('.product-link').attr('href'); // Add to our array if we have at least a title if (title) { productList.push({ title, price, imageUrl, productUrl, id: index.toString() }); } }); this.setState({ products: productList, isLoading: false }); } catch (error) { console.error('Error fetching or parsing data:', error); this.setState({ isLoading: false }); } }; componentDidMount() { this.fetchData(); } renderProductItem = ({ item }) => ( <View style={styles.productCard}> {item.imageUrl && <Image source={{ uri: item.imageUrl }} style={styles.productImage} />} <Text style={styles.productTitle}>{item.title}</Text> <Text style={styles.productPrice}>{item.price}</Text> </View> ); render() { if (this.state.isLoading) { return <Text style={styles.loadingText}>Loading products...</Text>; } return ( <FlatList data={this.state.products} renderItem={this.renderProductItem} keyExtractor={(item) => item.id} contentContainerStyle={styles.listContainer} /> ); } } const styles = StyleSheet.create({ listContainer: { padding: 10, }, productCard: { marginBottom: 15, borderWidth: 1, borderColor: '#eee', borderRadius: 8, padding: 10, }, productImage: { width: '100%', height: 200, borderRadius: 8, marginBottom: 10, }, productTitle: { fontSize: 16, fontWeight: '500', marginBottom: 5, }, productPrice: { fontSize: 18, fontWeight: 'bold', color: '#2ecc71', }, loadingText: { flex: 1, justifyContent: 'center', alignItems: 'center', fontSize: 18, paddingTop: 20, }, }); export default DealsPage;
Quick Notes to Keep in Mind:
- Selector Tweaks: I used common selectors like
.product-titleand.price, but you might need to adjust these to match the page’s actual HTML. Right-click product elements in your browser’s dev tools to inspect and grab the correct class names. - Error Handling: Added a try/catch block to handle network or parsing issues gracefully.
- Loading State: Added an
isLoadingstate to show a friendly message while data loads. - FlatList: Replaced the single
Textcomponent withFlatListto create a scrollable, user-friendly product list.
内容的提问来源于stack exchange,提问作者ristapk
相关产品推荐
相关产品推荐

